<?php

namespace App\Services;

use App\Models\Tenants\AccountCode;
use App\Models\Tenants\JournalEntryLine;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class AccountCodeService extends Service
{
    /**
     * 계정과목 목록 조회
     */
    public function index(array $params): array
    {
        $tenantId = $this->tenantId();

        $query = AccountCode::query()
            ->where('tenant_id', $tenantId);

        // 검색 (코드/이름)
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                    ->orWhere('name', 'like', "%{$search}%");
            });
        }

        // 분류 필터
        if (! empty($params['category'])) {
            $query->where('category', $params['category']);
        }

        return $query->orderBy('sort_order')->orderBy('code')->get()->toArray();
    }

    /**
     * 계정과목 등록
     */
    public function store(array $data): AccountCode
    {
        $tenantId = $this->tenantId();

        // 중복 코드 체크
        $exists = AccountCode::query()
            ->where('tenant_id', $tenantId)
            ->where('code', $data['code'])
            ->exists();

        if ($exists) {
            throw new BadRequestHttpException(__('error.account_subject.duplicate_code'));
        }

        $accountCode = new AccountCode;
        $accountCode->tenant_id = $tenantId;
        $accountCode->code = $data['code'];
        $accountCode->name = $data['name'];
        $accountCode->category = $data['category'] ?? null;
        $accountCode->sort_order = $data['sort_order'] ?? 0;
        $accountCode->is_active = true;
        $accountCode->save();

        return $accountCode;
    }

    /**
     * 계정과목 활성/비활성 토글
     */
    public function toggleStatus(int $id, bool $isActive): AccountCode
    {
        $tenantId = $this->tenantId();

        $accountCode = AccountCode::query()
            ->where('tenant_id', $tenantId)
            ->findOrFail($id);

        $accountCode->is_active = $isActive;
        $accountCode->save();

        return $accountCode;
    }

    /**
     * 계정과목 삭제 (사용 중이면 차단)
     */
    public function destroy(int $id): bool
    {
        $tenantId = $this->tenantId();

        $accountCode = AccountCode::query()
            ->where('tenant_id', $tenantId)
            ->findOrFail($id);

        // 전표에서 사용 중인지 확인
        $inUse = JournalEntryLine::query()
            ->where('tenant_id', $tenantId)
            ->where('account_code', $accountCode->code)
            ->exists();

        if ($inUse) {
            throw new BadRequestHttpException(__('error.account_subject.in_use'));
        }

        $accountCode->delete();

        return true;
    }
}
