<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Services\CardTransactionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 카드 거래 조회 컨트롤러
 */
class CardTransactionController extends Controller
{
    public function __construct(
        protected CardTransactionService $service
    ) {}

    /**
     * 카드 거래 목록 조회
     */
    public function index(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $params = $request->validate([
                'start_date' => 'nullable|date',
                'end_date' => 'nullable|date|after_or_equal:start_date',
                'card_id' => 'nullable|integer',
                'search' => 'nullable|string|max:100',
                'sort_by' => 'nullable|in:used_at,amount,merchant_name,created_at',
                'sort_dir' => 'nullable|in:asc,desc',
                'per_page' => 'nullable|integer|min:1|max:100',
                'page' => 'nullable|integer|min:1',
            ]);

            return $this->service->index($params);
        }, __('message.fetched'));
    }

    /**
     * 카드 거래 요약 통계
     */
    public function summary(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $params = $request->validate([
                'start_date' => 'nullable|date',
                'end_date' => 'nullable|date|after_or_equal:start_date',
            ]);

            return $this->service->summary($params);
        }, __('message.fetched'));
    }

    /**
     * 카드 거래 대시보드 데이터
     *
     * CEO 대시보드 카드/가지급금 관리 섹션의 cm1 모달용 상세 데이터
     */
    public function dashboard(): JsonResponse
    {
        return ApiResponse::handle(function () {
            return $this->service->dashboard();
        }, __('message.fetched'));
    }

    /**
     * 계정과목 일괄 수정
     */
    public function bulkUpdateAccountCode(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $validated = $request->validate([
                'ids' => 'required|array|min:1',
                'ids.*' => 'required|integer',
                'account_code' => 'required|string|max:20',
            ]);

            $updatedCount = $this->service->bulkUpdateAccountCode(
                $validated['ids'],
                $validated['account_code']
            );

            return ['updated_count' => $updatedCount];
        }, __('message.updated'));
    }

    /**
     * 단일 카드 거래 조회
     */
    public function show(int $id): JsonResponse
    {
        return ApiResponse::handle(function () use ($id) {
            $transaction = $this->service->show($id);

            if (! $transaction) {
                throw new \Illuminate\Database\Eloquent\ModelNotFoundException;
            }

            return $transaction;
        }, __('message.fetched'));
    }

    /**
     * 카드 거래 등록
     */
    public function store(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $validated = $request->validate([
                'card_id' => 'nullable|integer|exists:cards,id',
                'used_at' => 'required|date',
                'merchant_name' => 'required|string|max:100',
                'amount' => 'required|numeric|min:0',
                'description' => 'nullable|string|max:500',
                'account_code' => 'nullable|string|max:20',
            ]);

            return $this->service->store($validated);
        }, __('message.created'));
    }

    /**
     * 카드 거래 수정
     */
    public function update(Request $request, int $id): JsonResponse
    {
        return ApiResponse::handle(function () use ($request, $id) {
            $validated = $request->validate([
                'used_at' => 'nullable|date',
                'merchant_name' => 'nullable|string|max:100',
                'amount' => 'nullable|numeric|min:0',
                'description' => 'nullable|string|max:500',
                'account_code' => 'nullable|string|max:20',
            ]);

            return $this->service->update($id, $validated);
        }, __('message.updated'));
    }

    /**
     * 카드 거래 삭제
     */
    public function destroy(int $id): JsonResponse
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->service->destroy($id);
        }, __('message.deleted'));
    }
}
