package com.gcsc.connection.service.controller;

import com.gcsc.connection.common.dto.ApiResponse;
import com.gcsc.connection.service.dto.ApiDomainResponse;
import com.gcsc.connection.service.dto.SaveApiDomainRequest;
import com.gcsc.connection.service.entity.SnpApiDomain;
import com.gcsc.connection.service.repository.SnpApiDomainRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * API 도메인 관리 API
 */
@RestController
@RequestMapping("/api/domains")
@RequiredArgsConstructor
public class ApiDomainController {

    private final SnpApiDomainRepository snpApiDomainRepository;

    /**
     * 전체 도메인 목록 조회 (sortOrder 오름차순)
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<ApiDomainResponse>>> getDomains() {
        List<ApiDomainResponse> domains = snpApiDomainRepository.findAllByOrderBySortOrderAscDomainNameAsc()
            .stream()
            .map(ApiDomainResponse::from)
            .toList();
        return ResponseEntity.ok(ApiResponse.ok(domains));
    }

    /**
     * 도메인 생성
     */
    @PostMapping
    public ResponseEntity<ApiResponse<ApiDomainResponse>> createDomain(
            @RequestBody SaveApiDomainRequest request) {
        SnpApiDomain domain = SnpApiDomain.builder()
            .domainName(request.domainName())
            .iconPath(request.iconPath())
            .sortOrder(request.sortOrder())
            .build();
        SnpApiDomain saved = snpApiDomainRepository.save(domain);
        return ResponseEntity.ok(ApiResponse.ok(ApiDomainResponse.from(saved)));
    }

    /**
     * 도메인 수정
     */
    @PutMapping("/{domainId}")
    public ResponseEntity<ApiResponse<ApiDomainResponse>> updateDomain(
            @PathVariable Long domainId,
            @RequestBody SaveApiDomainRequest request) {
        SnpApiDomain domain = snpApiDomainRepository.findById(domainId)
            .orElseThrow(() -> new IllegalArgumentException("도메인을 찾을 수 없습니다: " + domainId));
        domain.update(request.domainName(), request.iconPath(), request.sortOrder());
        SnpApiDomain saved = snpApiDomainRepository.save(domain);
        return ResponseEntity.ok(ApiResponse.ok(ApiDomainResponse.from(saved)));
    }

    /**
     * 도메인 삭제
     */
    @DeleteMapping("/{domainId}")
    public ResponseEntity<ApiResponse<Void>> deleteDomain(@PathVariable Long domainId) {
        snpApiDomainRepository.deleteById(domainId);
        return ResponseEntity.ok(ApiResponse.ok(null));
    }
}
