package com.zioinfo.kintex.system.company;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.PageResponse;
import com.zioinfo.kintex.common.audit.Audited;
import com.zioinfo.kintex.system.SystemAccessGuard;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

/** 시스템관리 — 회사(거래처) 관리 API. ADMIN 게이트. 연락처 마스킹. */
@RestController
@RequestMapping("/api/admin/companies")
public class CompanyController {

    private final CompanyService service;
    private final SystemAccessGuard guard;

    public CompanyController(CompanyService service, SystemAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    @GetMapping
    public ApiResponse<PageResponse<CompanyDto>> list(
            @AuthenticationPrincipal KintexPrincipal principal,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String partnerType,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        guard.requireAdmin(principal);
        return ApiResponse.ok(service.list(keyword, partnerType, page, size));
    }

    @Audited(action = "COMPANY_SAVE", targetType = "company")
    @PostMapping
    public ApiResponse<Void> save(@AuthenticationPrincipal KintexPrincipal principal,
                                  @Valid @RequestBody CompanySaveRequest req) {
        guard.requireAdmin(principal);
        service.save(req);
        return ApiResponse.ok(null);
    }

    @Audited(action = "COMPANY_DELETE", targetType = "company")
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@AuthenticationPrincipal KintexPrincipal principal,
                                    @PathVariable String id) {
        guard.requireAdmin(principal);
        service.delete(id);
        return ApiResponse.ok(null);
    }
}
