package com.zioinfo.esn.controller;

import com.zioinfo.esn.auth.EsnUser;
import com.zioinfo.esn.common.ApiResponse;
import com.zioinfo.esn.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;

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

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

    @PostMapping
    public ApiResponse<EsnUser> create(@RequestBody Map<String, Object> body) {
        EsnUser user = new EsnUser();
        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");
        return ApiResponse.ok("사용자 생성 완료", service.create(user, rawPassword));
    }

    @PutMapping("/{id}")
    public ApiResponse<EsnUser> update(@PathVariable Long id, @RequestBody EsnUser v) {
        return ApiResponse.ok("사용자 수정 완료", service.update(id, v));
    }

    @PutMapping("/{id}/password")
    public ApiResponse<Void> changePassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
        service.changePassword(id, body.getOrDefault("password", "changeme123"));
        return ApiResponse.ok("비밀번호 변경 완료", null);
    }

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