<?php

namespace App\Services;

use App\Models\Tenants\Withdrawal;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

/**
 * 카드 거래 조회 서비스
 *
 * 카드 결제 내역 조회 및 계정과목 일괄 수정 기능 제공
 */
class CardTransactionService extends Service
{
    /**
     * 카드 거래 목록 조회
     *
     * @param  array{
     *     start_date?: string,
     *     end_date?: string,
     *     card_id?: int,
     *     search?: string,
     *     sort_by?: string,
     *     sort_dir?: string,
     *     per_page?: int,
     *     page?: int
     * }  $params
     */
    public function index(array $params = []): LengthAwarePaginator
    {
        $query = Withdrawal::query()
            ->where('payment_method', 'card')
            ->with(['card', 'card.assignedUser', 'creator']);

        // 날짜 필터
        if (! empty($params['start_date'])) {
            $query->where(function ($q) use ($params) {
                $q->whereDate('used_at', '>=', $params['start_date'])
                    ->orWhere(function ($q2) use ($params) {
                        $q2->whereNull('used_at')
                            ->whereDate('withdrawal_date', '>=', $params['start_date']);
                    });
            });
        }

        if (! empty($params['end_date'])) {
            $query->where(function ($q) use ($params) {
                $q->whereDate('used_at', '<=', $params['end_date'])
                    ->orWhere(function ($q2) use ($params) {
                        $q2->whereNull('used_at')
                            ->whereDate('withdrawal_date', '<=', $params['end_date']);
                    });
            });
        }

        // 카드 필터
        if (! empty($params['card_id'])) {
            $query->where('card_id', $params['card_id']);
        }

        // 검색 (카드번호, 가맹점명, 적요)
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('merchant_name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhereHas('card', function ($cardQ) use ($search) {
                        $cardQ->where('card_name', 'like', "%{$search}%")
                            ->orWhere('card_company', 'like', "%{$search}%");
                    });
            });
        }

        // 정렬
        $sortBy = $params['sort_by'] ?? 'used_at';
        $sortDir = $params['sort_dir'] ?? 'desc';

        // 정렬 필드 매핑
        $sortableFields = [
            'used_at' => DB::raw('COALESCE(used_at, withdrawal_date)'),
            'amount' => 'amount',
            'merchant_name' => 'merchant_name',
            'created_at' => 'created_at',
        ];

        if (array_key_exists($sortBy, $sortableFields)) {
            $query->orderBy($sortableFields[$sortBy], $sortDir);
        } else {
            $query->orderBy(DB::raw('COALESCE(used_at, withdrawal_date)'), 'desc');
        }

        $perPage = $params['per_page'] ?? 20;

        return $query->paginate($perPage);
    }

    /**
     * 카드 거래 요약 통계
     *
     * @param  array{start_date?: string, end_date?: string}  $params
     * @return array{
     *     previous_month_total: float,
     *     current_month_total: float,
     *     total_count: int,
     *     total_amount: float
     * }
     */
    public function summary(array $params = []): array
    {
        // 전월 기준일 계산
        $currentDate = now();
        $currentMonthStart = $currentDate->copy()->startOfMonth()->toDateString();
        $currentMonthEnd = $currentDate->copy()->endOfMonth()->toDateString();
        $previousMonthStart = $currentDate->copy()->subMonth()->startOfMonth()->toDateString();
        $previousMonthEnd = $currentDate->copy()->subMonth()->endOfMonth()->toDateString();

        // 전월 카드 사용액
        $previousMonthTotal = Withdrawal::query()
            ->where('payment_method', 'card')
            ->where(function ($q) use ($previousMonthStart, $previousMonthEnd) {
                $q->whereBetween(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), [$previousMonthStart, $previousMonthEnd]);
            })
            ->sum('amount');

        // 당월 카드 사용액
        $currentMonthTotal = Withdrawal::query()
            ->where('payment_method', 'card')
            ->where(function ($q) use ($currentMonthStart, $currentMonthEnd) {
                $q->whereBetween(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), [$currentMonthStart, $currentMonthEnd]);
            })
            ->sum('amount');

        // 조회 기간 내 총 건수/금액 (옵션)
        $periodQuery = Withdrawal::query()->where('payment_method', 'card');

        if (! empty($params['start_date'])) {
            $periodQuery->where(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $periodQuery->where(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), '<=', $params['end_date']);
        }

        $totalCount = $periodQuery->count();
        $totalAmount = (clone $periodQuery)->sum('amount');

        return [
            'previous_month_total' => (float) $previousMonthTotal,
            'current_month_total' => (float) $currentMonthTotal,
            'total_count' => $totalCount,
            'total_amount' => (float) $totalAmount,
        ];
    }

    /**
     * 계정과목 일괄 수정
     *
     * @param  array<int>  $ids  거래 ID 배열
     * @param  string  $accountCode  계정과목 코드
     * @return int 수정된 건수
     */
    public function bulkUpdateAccountCode(array $ids, string $accountCode): int
    {
        return Withdrawal::query()
            ->whereIn('id', $ids)
            ->where('payment_method', 'card')
            ->update([
                'account_code' => $accountCode,
                'updated_by' => $this->apiUserId(),
            ]);
    }

    /**
     * 단일 카드 거래 조회
     */
    public function show(int $id): ?Withdrawal
    {
        return Withdrawal::query()
            ->where('payment_method', 'card')
            ->with(['card', 'card.assignedUser', 'creator'])
            ->find($id);
    }
}
