package com.zioinfo.mall.subscription;

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

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/** 구독 API — /api/mall/subscription. 인증 고객 본인 구독. 전체 목록 MANAGER+. */
@RestController
@RequestMapping("/api/mall/subscription")
@RequiredArgsConstructor
public class SubscriptionController {

    private final SubscriptionMapper mapper;

    @GetMapping
    public ApiResponse<List<MallSubscription>> mine(Authentication auth) {
        return ApiResponse.ok(mapper.findByOwner(auth.getName()));
    }

    @GetMapping("/admin")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<MallSubscription>> all(@RequestParam(required = false) String status) {
        return ApiResponse.ok(mapper.findAll(status));
    }

    @PostMapping
    public ApiResponse<MallSubscription> subscribe(@RequestBody MallSubscription s, Authentication auth) {
        s.setOwner(auth.getName());
        if (s.getNextDeliveryDate() == null) {
            s.setNextDeliveryDate(nextDate(s.getFrequency()));
        }
        mapper.insert(s);
        return ApiResponse.ok(mapper.findById(s.getId()));
    }

    /** 구독 상태 변경(PAUSE/RESUME/CANCEL). 본인만. */
    @PutMapping("/{id}/status")
    public ApiResponse<MallSubscription> status(@PathVariable Long id, @RequestBody Map<String, String> req, Authentication auth) {
        MallSubscription s = mapper.findById(id);
        if (s == null || !s.getOwner().equals(auth.getName())) {
            throw new RuntimeException("ERR-SUB-403: 본인 구독만 변경할 수 있습니다");
        }
        String to = req.getOrDefault("status", "ACTIVE").toUpperCase();
        mapper.updateStatus(id, to);
        return ApiResponse.ok(mapper.findById(id));
    }

    private LocalDate nextDate(String freq) {
        LocalDate base = LocalDate.now();
        if ("MONTHLY".equalsIgnoreCase(freq)) return base.plusMonths(1);
        if ("BIWEEKLY".equalsIgnoreCase(freq)) return base.plusWeeks(2);
        return base.plusWeeks(1);
    }
}
