package com.zioinfo.mall.store;

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

import java.util.List;

/** 매장 API — /api/mall/store. 목록/상세 공개(스토어프론트), 변경 MANAGER+. */
@RestController
@RequestMapping("/api/mall/store")
@RequiredArgsConstructor
public class StoreController {

    private final StoreMapper mapper;
    private final AuditService auditService;

    /** 매장 목록 — 공개(픽업 선택용). */
    @GetMapping
    public ApiResponse<List<MallStore>> list(@RequestParam(defaultValue = "true") boolean activeOnly) {
        return ApiResponse.ok(mapper.findAll(activeOnly));
    }

    @GetMapping("/{id}")
    public ApiResponse<MallStore> get(@PathVariable Long id) {
        return ApiResponse.ok(mapper.findById(id));
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<MallStore> create(@RequestBody MallStore s) {
        mapper.insert(s);
        auditService.log("STORE_CREATE", s.getCode(), s.getName());
        return ApiResponse.ok(mapper.findById(s.getId()));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallStore> update(@PathVariable Long id, @RequestBody MallStore s) {
        s.setId(id);
        mapper.update(s);
        auditService.log("STORE_UPDATE", String.valueOf(id), s.getName());
        return ApiResponse.ok(mapper.findById(id));
    }

    @PutMapping("/{id}/active")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<MallStore> setActive(@PathVariable Long id, @RequestBody java.util.Map<String, Boolean> req) {
        boolean active = req.getOrDefault("active", true);
        mapper.setActive(id, active);
        auditService.log("STORE_ACTIVE", String.valueOf(id), String.valueOf(active));
        return ApiResponse.ok(mapper.findById(id));
    }
}
