<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Qms\AuditChecklistStoreRequest;
use App\Http\Requests\Qms\AuditChecklistUpdateRequest;
use App\Services\AuditChecklistService;
use Illuminate\Http\Request;

class AuditChecklistController extends Controller
{
    public function __construct(private AuditChecklistService $service) {}

    /**
     * 점검표 목록
     */
    public function index(Request $request)
    {
        return ApiResponse::handle(function () use ($request) {
            return $this->service->index($request->all());
        }, __('message.fetched'));
    }

    /**
     * 점검표 생성 (카테고리+항목 일괄)
     */
    public function store(AuditChecklistStoreRequest $request)
    {
        return ApiResponse::handle(function () use ($request) {
            return $this->service->store($request->validated());
        }, __('message.created'));
    }

    /**
     * 점검표 상세
     */
    public function show(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->service->show($id);
        }, __('message.fetched'));
    }

    /**
     * 점검표 수정
     */
    public function update(AuditChecklistUpdateRequest $request, int $id)
    {
        return ApiResponse::handle(function () use ($request, $id) {
            return $this->service->update($id, $request->validated());
        }, __('message.updated'));
    }

    /**
     * 점검표 완료 처리
     */
    public function complete(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->service->complete($id);
        }, __('message.updated'));
    }

    /**
     * 항목 완료/미완료 토글
     */
    public function toggleItem(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->service->toggleItem($id);
        }, __('message.updated'));
    }

    /**
     * 항목별 기준 문서 조회
     */
    public function itemDocuments(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->service->itemDocuments($id);
        }, __('message.fetched'));
    }

    /**
     * 기준 문서 연결
     */
    public function attachDocument(Request $request, int $id)
    {
        return ApiResponse::handle(function () use ($request, $id) {
            return $this->service->attachDocument($id, $request->validate([
                'title' => 'required|string|max:200',
                'version' => 'nullable|string|max:20',
                'date' => 'nullable|date',
                'document_id' => 'nullable|integer|exists:documents,id',
            ]));
        }, __('message.created'));
    }

    /**
     * 기준 문서 연결 해제
     */
    public function detachDocument(int $id, int $docId)
    {
        return ApiResponse::handle(function () use ($id, $docId) {
            $this->service->detachDocument($id, $docId);

            return null;
        }, __('message.deleted'));
    }
}
