<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\V1\Site\StoreSiteRequest;
use App\Http\Requests\V1\Site\UpdateSiteRequest;
use App\Services\SiteService;
use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function __construct(
        private readonly SiteService $service
    ) {}

    /**
     * 현장 목록
     */
    public function index(Request $request)
    {
        $params = $request->only([
            'search',
            'is_active',
            'status',
            'client_id',
            'start_date',
            'end_date',
            'sort_by',
            'sort_dir',
            'per_page',
            'page',
        ]);

        $sites = $this->service->index($params);

        return ApiResponse::success($sites, __('message.fetched'));
    }

    /**
     * 현장 통계
     */
    public function stats()
    {
        $stats = $this->service->stats();

        return ApiResponse::success($stats, __('message.fetched'));
    }

    /**
     * 현장 등록
     */
    public function store(StoreSiteRequest $request)
    {
        $site = $this->service->store($request->validated());

        return ApiResponse::success($site, __('message.created'), [], 201);
    }

    /**
     * 현장 상세
     */
    public function show(int $id)
    {
        $site = $this->service->show($id);

        return ApiResponse::success($site, __('message.fetched'));
    }

    /**
     * 현장 수정
     */
    public function update(int $id, UpdateSiteRequest $request)
    {
        $site = $this->service->update($id, $request->validated());

        return ApiResponse::success($site, __('message.updated'));
    }

    /**
     * 현장 삭제
     */
    public function destroy(int $id)
    {
        $this->service->destroy($id);

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

    /**
     * 현장 일괄 삭제
     */
    public function bulkDestroy(Request $request)
    {
        $ids = $request->input('ids', []);

        if (empty($ids)) {
            return ApiResponse::error(__('error.no_items_selected'), 400);
        }

        $deletedCount = $this->service->bulkDestroy($ids);

        return ApiResponse::success(
            ['deleted_count' => $deletedCount],
            __('message.deleted')
        );
    }

    /**
     * 활성화된 현장 목록 (셀렉트박스용)
     */
    public function active()
    {
        $sites = $this->service->getActiveSites();

        return ApiResponse::success($sites, __('message.fetched'));
    }
}
