package com.zioinfo.signage.controller;

import com.zioinfo.signage.admin.AuditService;
import com.zioinfo.signage.common.ApiResponse;
import com.zioinfo.signage.domain.FirmwareVo;
import com.zioinfo.signage.service.FirmwareService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/firmware")
@RequiredArgsConstructor
public class FirmwareController {
    private final FirmwareService service;
    private final AuditService audit;

    @GetMapping
    public ApiResponse<List<FirmwareVo>> list(
            @RequestParam(required = false) String tenantCode,
            @RequestParam(required = false) String deviceType) {
        return ApiResponse.ok(service.list(tenantCode, deviceType));
    }

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

    @PostMapping
    public ApiResponse<FirmwareVo> create(@RequestBody FirmwareVo v) {
        FirmwareVo created = service.create(v);
        // ESL 펌웨어 배포 — 추적 가치 높음
        audit.log(created.getTenantCode(), "FIRMWARE_DEPLOY", "FIRMWARE", String.valueOf(created.getId()),
                "deviceType=" + created.getDeviceType() + ", version=" + created.getFirmwareVersion()
                        + ", latest=" + created.isLatest(), true);
        return ApiResponse.ok("펌웨어 등록 완료", created);
    }

    @PutMapping("/{id}")
    public ApiResponse<FirmwareVo> update(@PathVariable Long id, @RequestBody FirmwareVo v) {
        FirmwareVo updated = service.update(id, v);
        audit.log(updated.getTenantCode(), "FIRMWARE_UPDATE", "FIRMWARE", String.valueOf(id),
                "deviceType=" + updated.getDeviceType() + ", version=" + updated.getFirmwareVersion()
                        + ", latest=" + updated.isLatest(), true);
        return ApiResponse.ok("펌웨어 수정 완료", updated);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        service.delete(id);
        audit.log(null, "FIRMWARE_DELETE", "FIRMWARE", String.valueOf(id), "펌웨어 삭제", true);
        return ApiResponse.ok("펌웨어 삭제 완료", null);
    }
}
