package com.zioinfo.kintex.auth;

import com.zioinfo.kintex.auth.dto.AcceptInviteRequest;
import com.zioinfo.kintex.auth.dto.LoginRequest;
import com.zioinfo.kintex.auth.dto.LoginResponse;
import com.zioinfo.kintex.auth.dto.MeResponse;
import com.zioinfo.kintex.auth.dto.WorkspaceDto;
import com.zioinfo.kintex.common.ApiResponse;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 인증·워크스페이스 API (C-1 / SCR-01). */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;
    private final EventAccessGuard guard;

    public AuthController(AuthService authService, EventAccessGuard guard) {
        this.authService = authService;
        this.guard = guard;
    }

    /** POST /api/auth/login — 이메일/비밀번호 로그인 → 토큰 + 워크스페이스. */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        return ApiResponse.ok(authService.login(request));
    }

    /** GET /api/auth/workspaces — 내 참여 행사 목록(SCR-01 카드 그리드). */
    @GetMapping("/workspaces")
    public ApiResponse<List<WorkspaceDto>> workspaces(@AuthenticationPrincipal KintexPrincipal principal) {
        guard.require(principal);
        return ApiResponse.ok(authService.listWorkspaces(principal));
    }

    /** POST /api/auth/accept-invite — 초대 수락(장치업체는 등록업체 검증). */
    @PostMapping("/accept-invite")
    public ApiResponse<LoginResponse> acceptInvite(@AuthenticationPrincipal KintexPrincipal principal,
                                                   @Valid @RequestBody AcceptInviteRequest request) {
        guard.require(principal);
        return ApiResponse.ok(authService.acceptInvite(principal, request));
    }

    /**
     * GET /api/auth/me — 현재 토큰의 신원·행사별 역할 + 프로필(email·phone·deptId·photoUrl) 순증.
     * 기존 principal 필드의 상위집합이라 웹 부트스트랩 회귀 0(계약: {@link MeResponse}).
     */
    @GetMapping("/me")
    public ApiResponse<MeResponse> me(@AuthenticationPrincipal KintexPrincipal principal) {
        guard.require(principal);
        return ApiResponse.ok(authService.me(principal));
    }
}
