package com.zioinfo.mall.zone;

import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.store.MallStore;
import com.zioinfo.mall.store.mapper.StoreMapper;
import com.zioinfo.mall.zone.mapper.ZoneMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 배송권역 API — /api/mall/zone.
 * ZIP 조회(고객 진입 필터, 공개)는 가용 매장과 배송 가능 여부를 판정한다(Floom 패턴).
 */
@RestController
@RequestMapping("/api/mall/zone")
@RequiredArgsConstructor
public class ZoneController {

    private final ZoneMapper mapper;
    private final StoreMapper storeMapper;

    /**
     * ZIP 진입 조회 — 공개. 해당 ZIP을 커버하는 매장 목록과 deliverable 판정.
     * 응답: { zip, deliverable, stores:[{storeId,storeName,radiusMi}] }
     */
    @GetMapping("/lookup")
    public ApiResponse<Map<String, Object>> lookup(@RequestParam String zip) {
        List<MallZone> zones = mapper.findByZip(zip);
        List<Map<String, Object>> stores = new ArrayList<>();
        for (MallZone z : zones) {
            MallStore s = storeMapper.findById(z.getStoreId());
            if (s == null || Boolean.FALSE.equals(s.getActive())) continue;
            Map<String, Object> m = new LinkedHashMap<>();
            m.put("storeId", s.getId());
            m.put("storeCode", s.getCode());
            m.put("storeName", s.getName());
            m.put("radiusMi", z.getRadiusMi());
            m.put("sameDayCutoff", s.getSameDayCutoff());
            m.put("timezone", s.getTimezone());
            stores.add(m);
        }
        Map<String, Object> out = new LinkedHashMap<>();
        out.put("zip", zip);
        out.put("deliverable", !stores.isEmpty());
        out.put("stores", stores);
        return ApiResponse.ok(out);
    }

    @GetMapping
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<MallZone>> list(@RequestParam(required = false) Long storeId) {
        return ApiResponse.ok(storeId != null ? mapper.findByStore(storeId) : mapper.findAll());
    }

    @PostMapping
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallZone> create(@RequestBody MallZone z) {
        mapper.insert(z);
        return ApiResponse.ok(z);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<String> delete(@PathVariable Long id) {
        mapper.delete(id);
        return ApiResponse.ok("deleted");
    }
}
