package com.zioinfo.mall.event;

import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.loyalty.LoyaltyService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 이벤트/캠페인 API — /api/mall/event.
 *
 * <ul>
 *   <li>진행중 이벤트/배너 조회 — 공개(스토어프론트)</li>
 *   <li>참여(쿠폰 발급) — 인증 고객</li>
 *   <li>이벤트 정의 CRUD·발행·성과·AI 카피 — MANAGER+ (정의/발행) · ADMIN(삭제)</li>
 * </ul>
 * 공개 GET 화이트리스트는 SecurityConfig 에 등록.
 */
@RestController
@RequestMapping("/api/mall/event")
@RequiredArgsConstructor
public class EventController {

    private final EventService service;
    private final LoyaltyService loyaltyService;

    // ---------- 공개 스토어프론트 ----------
    /** 진행중 이벤트(등급 필터 옵션). */
    @GetMapping("/ongoing")
    public ApiResponse<List<MallEvent>> ongoing(@RequestParam(required = false) String tier) {
        return ApiResponse.ok(service.ongoing(tier));
    }

    /** 진행중 이벤트 배너(홈 캐러셀). */
    @GetMapping("/banners")
    public ApiResponse<List<MallEventBanner>> banners() {
        return ApiResponse.ok(service.activeBanners());
    }

    @GetMapping("/{id}")
    public ApiResponse<MallEvent> detail(@PathVariable Long id) {
        return ApiResponse.ok(service.detail(id));
    }

    // ---------- 참여 (인증) ----------
    /** 이벤트 참여 — 현재 등급 기준 자격 검증 후 연계 쿠폰 발급. */
    @PostMapping("/{id}/join")
    public ApiResponse<Map<String, Object>> join(@PathVariable Long id, Authentication auth) {
        String tier = loyaltyService.currentTierCode(auth.getName());
        return ApiResponse.ok(service.join(id, auth.getName(), tier));
    }

    // ---------- 관리자 (MANAGER+) ----------
    @GetMapping
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<MallEvent>> list(@RequestParam(required = false) String status,
                                             @RequestParam(required = false) String type,
                                             @RequestParam(defaultValue = "false") boolean activeOnly) {
        return ApiResponse.ok(service.list(status, type, activeOnly));
    }

    @PostMapping
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallEvent> create(@RequestBody MallEvent e, Authentication auth) {
        return ApiResponse.ok(service.create(e, auth.getName()));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallEvent> update(@PathVariable Long id, @RequestBody MallEvent e, Authentication auth) {
        return ApiResponse.ok(service.update(id, e, auth.getName()));
    }

    @PostMapping("/{id}/publish")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallEvent> publish(@PathVariable Long id, Authentication auth) {
        return ApiResponse.ok(service.publish(id, auth.getName()));
    }

    @PostMapping("/{id}/end")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallEvent> end(@PathVariable Long id, Authentication auth) {
        return ApiResponse.ok(service.end(id, auth.getName()));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> delete(@PathVariable Long id, Authentication auth) {
        service.delete(id, auth.getName());
        return ApiResponse.ok(null);
    }

    /** 이벤트 성과(참여/매출). */
    @GetMapping("/{id}/performance")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<Map<String, Object>> performance(@PathVariable Long id) {
        return ApiResponse.ok(service.performance(id));
    }

    /** AI 이벤트 카피 보조(헤드라인/서브). */
    @PostMapping("/ai/copy")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<Map<String, Object>> copy(@RequestBody CopyRequest req) {
        return ApiResponse.ok(service.copyAssist(req.eventType(), req.theme(), req.tone()));
    }

    public record CopyRequest(String eventType, String theme, String tone) {}
}
