package com.zioinfo.signage.controller;

import com.zioinfo.signage.admin.AuditService;
import com.zioinfo.signage.auth.SignageUser;
import com.zioinfo.signage.common.ApiResponse;
import com.zioinfo.signage.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    private final UserService service;
    private final AuditService audit;

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

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

    @PostMapping
    public ApiResponse<SignageUser> create(@RequestBody Map<String, Object> body) {
        SignageUser user = new SignageUser();
        user.setUsername((String) body.get("username"));
        user.setRole((String) body.getOrDefault("role", "USER"));
        user.setTenantCode((String) body.get("tenantCode"));
        user.setEmail((String) body.get("email"));
        user.setPhone((String) body.get("phone"));
        user.setActive(true);
        String rawPassword = (String) body.getOrDefault("password", "changeme123");
        SignageUser created = service.create(user, rawPassword);
        // 보안: 비밀번호는 감사 detail 에 절대 기록하지 않는다(username/role/tenant 요약만).
        audit.log(created.getTenantCode(), "USER_CREATE", "USER", String.valueOf(created.getId()),
                "username=" + created.getUsername() + ", role=" + created.getRole(), true);
        return ApiResponse.ok("사용자 생성 완료", created);
    }

    @PutMapping("/{id}")
    public ApiResponse<SignageUser> update(@PathVariable Long id, @RequestBody SignageUser v) {
        SignageUser updated = service.update(id, v);
        audit.log(updated.getTenantCode(), "USER_UPDATE", "USER", String.valueOf(id),
                "role=" + updated.getRole() + ", active=" + updated.isActive(), true);
        return ApiResponse.ok("사용자 수정 완료", updated);
    }

    @PutMapping("/{id}/password")
    public ApiResponse<Void> changePassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
        service.changePassword(id, body.getOrDefault("password", "changeme123"));
        // 보안: 새 비밀번호 값은 기록하지 않는다(대상 id 만).
        audit.log(null, "USER_PASSWORD_RESET", "USER", String.valueOf(id), "비밀번호 초기화", true);
        return ApiResponse.ok("비밀번호 변경 완료", null);
    }

    @PutMapping("/{id}/active")
    public ApiResponse<SignageUser> setActive(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        boolean active = Boolean.TRUE.equals(body.get("active"));
        SignageUser u = service.setActive(id, active);
        audit.log(u != null ? u.getTenantCode() : null, "USER_ACTIVE_TOGGLE", "USER",
                String.valueOf(id), "active=" + active, true);
        return ApiResponse.ok(active ? "활성화 완료" : "비활성화 완료", u);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        service.delete(id);
        audit.log(null, "USER_DELETE", "USER", String.valueOf(id), "사용자 삭제", true);
        return ApiResponse.ok("사용자 삭제 완료", null);
    }
}
