package com.zioinfo.kintex.visitor.contact;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.visitor.VisitorAuth;
import com.zioinfo.kintex.visitor.contact.ContactDtos.ContactDto;
import com.zioinfo.kintex.visitor.contact.ContactDtos.ExchangeRequest;
import com.zioinfo.kintex.visitor.contact.ContactDtos.MyCardDto;
import com.zioinfo.kintex.visitor.contact.ContactDtos.SaveCardRequest;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * F-C4 관람객 QR 명함 교환·컨택트 지갑 API — 인증(본인 지갑만).
 */
@RestController
@RequestMapping("/api/visitor/contacts")
public class ContactController {

    private final ContactService service;

    public ContactController(ContactService service) {
        this.service = service;
    }

    /** GET /me/card — 내 명함(QR 공유 토큰). 없으면 자동 생성. */
    @GetMapping("/me/card")
    public ApiResponse<MyCardDto> myCard(@AuthenticationPrincipal KintexPrincipal principal) {
        return ApiResponse.ok(service.myCard(VisitorAuth.requireUserId(principal), principal.displayName()));
    }

    /** PUT /me/card — 내 명함 저장/수정. */
    @PutMapping("/me/card")
    public ApiResponse<MyCardDto> saveCard(@AuthenticationPrincipal KintexPrincipal principal,
                                           @Valid @RequestBody SaveCardRequest req) {
        return ApiResponse.ok(service.saveCard(VisitorAuth.requireUserId(principal), req));
    }

    /** POST /exchange — 상대 QR 스캔 교환(상호 저장). */
    @PostMapping("/exchange")
    public ApiResponse<ContactDto> exchange(@AuthenticationPrincipal KintexPrincipal principal,
                                            @Valid @RequestBody ExchangeRequest req) {
        return ApiResponse.ok(service.exchange(
                VisitorAuth.requireUserId(principal), principal.displayName(), req.qrPayload()));
    }

    /** GET / — 내 컨택트 지갑. */
    @GetMapping
    public ApiResponse<List<ContactDto>> list(@AuthenticationPrincipal KintexPrincipal principal) {
        return ApiResponse.ok(service.list(VisitorAuth.requireUserId(principal)));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@AuthenticationPrincipal KintexPrincipal principal, @PathVariable String id) {
        service.delete(VisitorAuth.requireUserId(principal), id);
        return ApiResponse.ok(null);
    }
}
