<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Client\ClientStoreRequest;
use App\Http\Requests\Client\ClientUpdateRequest;
use App\Services\ClientService;
use Illuminate\Http\Request;

class ClientController extends Controller
{
    public function __construct(private ClientService $service) {}

    public function index(Request $request)
    {
        return ApiResponse::handle(function () use ($request) {
            return $this->service->index($request->all());
        }, __('message.client.fetched'));
    }

    public function show(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->service->show($id);
        }, __('message.client.fetched'));
    }

    public function store(ClientStoreRequest $request)
    {
        return ApiResponse::handle(function () use ($request) {
            return $this->service->store($request->validated());
        }, __('message.client.created'));
    }

    public function update(ClientUpdateRequest $request, int $id)
    {
        return ApiResponse::handle(function () use ($request, $id) {
            return $this->service->update($id, $request->validated());
        }, __('message.client.updated'));
    }

    public function destroy(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            $this->service->destroy($id);

            return 'success';
        }, __('message.client.deleted'));
    }

    public function toggle(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->service->toggle($id);
        }, __('message.client.toggled'));
    }

    /**
     * 거래처 통계
     */
    public function stats()
    {
        return ApiResponse::handle(function () {
            return $this->service->stats();
        }, __('message.fetched'));
    }

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

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

        return ApiResponse::handle(function () use ($ids) {
            $deletedCount = $this->service->bulkDestroy($ids);

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