package com.goldenchart.controller;

import com.goldenchart.dto.LoginRequest;
import com.goldenchart.dto.LoginResponse;
import com.goldenchart.dto.MenuPermissionsResponse;
import com.goldenchart.service.AuthService;
import com.goldenchart.service.RolePermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final RolePermissionService rolePermissionService;

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest body) {
        return ResponseEntity.ok(authService.login(body.getUsername(), body.getPassword()));
    }

    @GetMapping("/me")
    public ResponseEntity<LoginResponse> me(
            @RequestHeader(value = "X-User-Id", required = false) String userIdHeader) {
        Long userId = parseUserId(userIdHeader);
        return authService.me(userId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /** 로그인 사용자 역할·메뉴 권한 (미로그인 시 GUEST) */
    @GetMapping("/menu-permissions")
    public MenuPermissionsResponse menuPermissions(
            @RequestHeader(value = "X-User-Id", required = false) String userIdHeader) {
        return rolePermissionService.resolveForUserId(parseUserId(userIdHeader));
    }

    private Long parseUserId(String header) {
        if (header == null || header.isBlank()) return null;
        try { return Long.parseLong(header); } catch (NumberFormatException e) { return null; }
    }
}
