package com.zioinfo.esn.controller;

import com.zioinfo.esn.admin.AuditService;
import com.zioinfo.esn.common.ApiResponse;
import com.zioinfo.esn.domain.TenantVo;
import com.zioinfo.esn.service.TenantService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/tenants")
@RequiredArgsConstructor
public class TenantController {
    private final TenantService service;
    private final AuditService audit;

    @GetMapping
    public ApiResponse<List<TenantVo>> list() {
        return ApiResponse.ok(service.list());
    }

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

    @PostMapping
    public ApiResponse<TenantVo> create(@RequestBody TenantVo v) {
        TenantVo created = service.create(v);
        audit.log(created.getTenantCode(), "TENANT_CREATE", "TENANT", String.valueOf(created.getId()),
                "name=" + created.getTenantName(), true);
        return ApiResponse.ok("테넌트 생성 완료", created);
    }

    @PutMapping("/{id}")
    public ApiResponse<TenantVo> update(@PathVariable Long id, @RequestBody TenantVo v) {
        TenantVo updated = service.update(id, v);
        audit.log(updated.getTenantCode(), "TENANT_UPDATE", "TENANT", String.valueOf(id),
                "name=" + updated.getTenantName(), true);
        return ApiResponse.ok("테넌트 수정 완료", updated);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        service.delete(id);
        audit.log(null, "TENANT_DELETE", "TENANT", String.valueOf(id), "테넌트 삭제", true);
        return ApiResponse.ok("테넌트 삭제 완료", null);
    }
}
