package com.honey.honey.controller;

import com.honey.honey.dto.AdminLoginRequest;
import com.honey.honey.dto.AdminLoginResponse;
import com.honey.honey.dto.ChatwootSessionRequest;
import com.honey.honey.security.admin.JwtUtil;
import com.honey.honey.service.AdminService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminLoginController {

    private final AdminService adminService;
    private final JwtUtil jwtUtil;

    /** Shared secret with Chatwoot. Set via env CHATWOOT_INTEGRATION_SECRET (e.g. from VPS secret file). */
    @Value("${CHATWOOT_INTEGRATION_SECRET:}")
    private String chatwootIntegrationSecret;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody AdminLoginRequest request) {
        if (request.getUsername() == null || request.getPassword() == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("Username and password are required");
        }

        Optional<String> tokenOpt = adminService.authenticate(
                request.getUsername(),
                request.getPassword()
        );

        if (tokenOpt.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body("Invalid credentials");
        }

        // Get admin to retrieve role
        var adminOpt = adminService.getAdminByUsername(request.getUsername());
        String role = adminOpt.map(admin -> admin.getRole()).orElse("ROLE_ADMIN");

        return ResponseEntity.ok(new AdminLoginResponse(
                tokenOpt.get(),
                request.getUsername(),
                role
        ));
    }

    /**
     * Exchanges a Chatwoot integration API key for an admin JWT with ROLE_SUPPORT.
     * Used when the admin panel is embedded in Chatwoot as a Dashboard App iframe.
     * API key must match CHATWOOT_INTEGRATION_SECRET on the server.
     */
    @PostMapping("/chatwoot-session")
    public ResponseEntity<?> chatwootSession(@RequestBody ChatwootSessionRequest request) {
        if (request.getApiKey() == null || request.getApiKey().isBlank()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("apiKey is required");
        }
        if (chatwootIntegrationSecret == null || chatwootIntegrationSecret.isBlank()) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Chatwoot integration is not configured (CHATWOOT_INTEGRATION_SECRET)");
        }
        if (!chatwootIntegrationSecret.equals(request.getApiKey().trim())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid apiKey");
        }
        String token = jwtUtil.generateTokenWithRole("__chatwoot__", "ROLE_SUPPORT");
        return ResponseEntity.ok(new AdminLoginResponse(
                token,
                "__chatwoot__",
                "ROLE_SUPPORT"
        ));
    }
}

