package mx.gob.slp.baseadminweb.web.controller;

import mx.gob.slp.baseadminweb.application.service.PassCodeService;
import mx.gob.slp.baseadminweb.domain.model.PassCode;
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.Map;

@RestController
@RequestMapping("/api/pass-codes")
public class PassCodeApiController {

    private final PassCodeService passCodeService;

    public PassCodeApiController(PassCodeService passCodeService) {
        this.passCodeService = passCodeService;
    }

    @PostMapping("/scan")
    public ResponseEntity<Map<String, Object>> scan(@RequestBody ScanRequest request) {
        try {
            PassCode passCode = passCodeService.scan(request.code());
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "Codigo pase escaneado correctamente.",
                    "passCode", toResponse(passCode)
            ));
        } catch (IllegalArgumentException | IllegalStateException ex) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", ex.getMessage()
            ));
        }
    }

    private Map<String, Object> toResponse(PassCode passCode) {
        return Map.of(
                "id", passCode.getId(),
                "name", passCode.getName(),
                "code", passCode.getCode(),
                "status", passCode.getStatus().name(),
                "scanned", passCode.isScanned(),
                "createdAt", passCode.getCreatedAt().toString(),
                "scannedAt", passCode.getScannedAt() == null ? "" : passCode.getScannedAt().toString()
        );
    }

    public record ScanRequest(String code) {
    }
}