<?php

namespace App\Services;

use App\Models\Tenants\AccountCode;
use App\Models\Tenants\JournalEntryLine;
use Illuminate\Support\Facades\DB;
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']);
        }

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

        // 부문 필터
        if (! empty($params['department_type'])) {
            $query->where('department_type', $params['department_type']);
        }

        // 계층 필터
        if (! empty($params['depth'])) {
            $query->where('depth', (int) $params['depth']);
        }

        // 활성 상태 필터
        if (isset($params['is_active'])) {
            $query->where('is_active', filter_var($params['is_active'], FILTER_VALIDATE_BOOLEAN));
        }

        // 선택 가능한 계정만 (소분류만 = Select용)
        if (! empty($params['selectable'])) {
            $query->selectable();
        }

        return $query->orderBy('code')->orderBy('sort_order')->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->sub_category = $data['sub_category'] ?? null;
        $accountCode->parent_code = $data['parent_code'] ?? null;
        $accountCode->depth = $data['depth'] ?? AccountCode::DEPTH_MINOR;
        $accountCode->department_type = $data['department_type'] ?? AccountCode::DEPT_COMMON;
        $accountCode->description = $data['description'] ?? null;
        $accountCode->sort_order = $data['sort_order'] ?? 0;
        $accountCode->is_active = true;
        $accountCode->save();

        return $accountCode;
    }

    /**
     * 계정과목 수정
     */
    public function update(int $id, array $data): AccountCode
    {
        $tenantId = $this->tenantId();

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

        // 코드 변경 시 중복 체크
        if (isset($data['code']) && $data['code'] !== $accountCode->code) {
            $exists = AccountCode::query()
                ->where('tenant_id', $tenantId)
                ->where('code', $data['code'])
                ->where('id', '!=', $id)
                ->exists();

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

        $accountCode->fill($data);
        $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;
    }

    /**
     * 기본 계정과목표 일괄 생성 (초기 세팅)
     */
    public function seedDefaults(): int
    {
        $tenantId = $this->tenantId();

        $defaults = $this->getDefaultAccountCodes();
        $insertedCount = 0;

        DB::transaction(function () use ($tenantId, $defaults, &$insertedCount) {
            foreach ($defaults as $item) {
                $exists = AccountCode::query()
                    ->where('tenant_id', $tenantId)
                    ->where('code', $item['code'])
                    ->exists();

                if (! $exists) {
                    AccountCode::create(array_merge($item, ['tenant_id' => $tenantId]));
                    $insertedCount++;
                }
            }
        });

        return $insertedCount;
    }

    /**
     * 기본 계정과목표 데이터 (더존 Smart A 표준 기반)
     *
     * 코드 체계: 5자리 (10100~99900)
     * - 10100~24000: 자산
     * - 25000~31700: 부채
     * - 33100~38700: 자본
     * - 40100~41000: 매출
     * - 50100~53700: 매출원가/제조경비 (제조부문)
     * - 80100~84800: 판매비와관리비 (관리부문)
     * - 90100~99900: 영업외수익/비용
     *
     * 계층: depth 1(대분류) → depth 2(중분류) → depth 3(소분류=더존 실제코드)
     */
    private function getDefaultAccountCodes(): array
    {
        $c = fn ($code, $name, $cat, $sub, $parent, $depth, $dept, $sort) => [
            'code' => $code, 'name' => $name, 'category' => $cat,
            'sub_category' => $sub, 'parent_code' => $parent,
            'depth' => $depth, 'department_type' => $dept, 'sort_order' => $sort,
        ];

        return [
            // ============================================================
            // 자산 (Assets)
            // ============================================================
            $c('1', '자산', 'asset', null, null, 1, 'common', 100),

            // -- 유동자산 --
            $c('11', '유동자산', 'asset', 'current_asset', '1', 2, 'common', 110),
            $c('10100', '현금', 'asset', 'current_asset', '11', 3, 'common', 1010),
            $c('10200', '당좌예금', 'asset', 'current_asset', '11', 3, 'common', 1020),
            $c('10300', '보통예금', 'asset', 'current_asset', '11', 3, 'common', 1030),
            $c('10400', '기타제예금', 'asset', 'current_asset', '11', 3, 'common', 1040),
            $c('10500', '정기적금', 'asset', 'current_asset', '11', 3, 'common', 1050),
            $c('10800', '외상매출금', 'asset', 'current_asset', '11', 3, 'common', 1080),
            $c('10900', '대손충당금(외상매출금)', 'asset', 'current_asset', '11', 3, 'common', 1090),
            $c('11000', '받을어음', 'asset', 'current_asset', '11', 3, 'common', 1100),
            $c('11400', '단기대여금', 'asset', 'current_asset', '11', 3, 'common', 1140),
            $c('11600', '미수수익', 'asset', 'current_asset', '11', 3, 'common', 1160),
            $c('12000', '미수금', 'asset', 'current_asset', '11', 3, 'common', 1200),
            $c('12200', '소모품', 'asset', 'current_asset', '11', 3, 'common', 1220),
            $c('12500', '미환급세금', 'asset', 'current_asset', '11', 3, 'common', 1250),
            $c('13100', '선급금', 'asset', 'current_asset', '11', 3, 'common', 1310),
            $c('13300', '선급비용', 'asset', 'current_asset', '11', 3, 'common', 1330),
            $c('13400', '가지급금', 'asset', 'current_asset', '11', 3, 'common', 1340),
            $c('13500', '부가세대급금', 'asset', 'current_asset', '11', 3, 'common', 1350),
            $c('13600', '선납세금', 'asset', 'current_asset', '11', 3, 'common', 1360),
            $c('14000', '선납법인세', 'asset', 'current_asset', '11', 3, 'common', 1400),

            // -- 재고자산 --
            $c('12', '재고자산', 'asset', 'current_asset', '1', 2, 'common', 120),
            $c('14600', '상품', 'asset', 'current_asset', '12', 3, 'common', 1460),
            $c('15000', '제품', 'asset', 'current_asset', '12', 3, 'common', 1500),
            $c('15300', '원재료', 'asset', 'current_asset', '12', 3, 'common', 1530),
            $c('16200', '부재료', 'asset', 'current_asset', '12', 3, 'common', 1620),
            $c('16700', '저장품', 'asset', 'current_asset', '12', 3, 'common', 1670),
            $c('16900', '재공품', 'asset', 'current_asset', '12', 3, 'common', 1690),

            // -- 비유동자산 --
            $c('13', '비유동자산', 'asset', 'fixed_asset', '1', 2, 'common', 130),
            $c('17600', '장기성예금', 'asset', 'fixed_asset', '13', 3, 'common', 1760),
            $c('17900', '장기대여금', 'asset', 'fixed_asset', '13', 3, 'common', 1790),
            $c('18700', '투자부동산', 'asset', 'fixed_asset', '13', 3, 'common', 1870),
            $c('19200', '단체퇴직보험예치금', 'asset', 'fixed_asset', '13', 3, 'common', 1920),
            $c('20100', '토지', 'asset', 'fixed_asset', '13', 3, 'common', 2010),
            $c('20200', '건물', 'asset', 'fixed_asset', '13', 3, 'common', 2020),
            $c('20300', '감가상각누계액(건물)', 'asset', 'fixed_asset', '13', 3, 'common', 2030),
            $c('20400', '구축물', 'asset', 'fixed_asset', '13', 3, 'common', 2040),
            $c('20500', '감가상각누계액(구축물)', 'asset', 'fixed_asset', '13', 3, 'common', 2050),
            $c('20600', '기계장치', 'asset', 'fixed_asset', '13', 3, 'common', 2060),
            $c('20700', '감가상각누계액(기계장치)', 'asset', 'fixed_asset', '13', 3, 'common', 2070),
            $c('20800', '차량운반구', 'asset', 'fixed_asset', '13', 3, 'common', 2080),
            $c('20900', '감가상각누계액(차량운반구)', 'asset', 'fixed_asset', '13', 3, 'common', 2090),
            $c('21000', '공구와기구', 'asset', 'fixed_asset', '13', 3, 'common', 2100),
            $c('21200', '비품', 'asset', 'fixed_asset', '13', 3, 'common', 2120),
            $c('21300', '건설중인자산', 'asset', 'fixed_asset', '13', 3, 'common', 2130),
            $c('24000', '소프트웨어', 'asset', 'fixed_asset', '13', 3, 'common', 2400),

            // ============================================================
            // 부채 (Liabilities)
            // ============================================================
            $c('2', '부채', 'liability', null, null, 1, 'common', 200),

            // -- 유동부채 --
            $c('21', '유동부채', 'liability', 'current_liability', '2', 2, 'common', 210),
            $c('25100', '외상매입금', 'liability', 'current_liability', '21', 3, 'common', 2510),
            $c('25200', '지급어음', 'liability', 'current_liability', '21', 3, 'common', 2520),
            $c('25300', '미지급금', 'liability', 'current_liability', '21', 3, 'common', 2530),
            $c('25400', '예수금', 'liability', 'current_liability', '21', 3, 'common', 2540),
            $c('25500', '부가세예수금', 'liability', 'current_liability', '21', 3, 'common', 2550),
            $c('25900', '선수금', 'liability', 'current_liability', '21', 3, 'common', 2590),
            $c('26000', '단기차입금', 'liability', 'current_liability', '21', 3, 'common', 2600),
            $c('26100', '미지급세금', 'liability', 'current_liability', '21', 3, 'common', 2610),
            $c('26200', '미지급비용', 'liability', 'current_liability', '21', 3, 'common', 2620),
            $c('26400', '유동성장기차입금', 'liability', 'current_liability', '21', 3, 'common', 2640),
            $c('26500', '미지급배당금', 'liability', 'current_liability', '21', 3, 'common', 2650),

            // -- 비유동부채 --
            $c('22', '비유동부채', 'liability', 'long_term_liability', '2', 2, 'common', 220),
            $c('29300', '장기차입금', 'liability', 'long_term_liability', '22', 3, 'common', 2930),
            $c('29400', '임대보증금', 'liability', 'long_term_liability', '22', 3, 'common', 2940),
            $c('29500', '퇴직급여충당부채', 'liability', 'long_term_liability', '22', 3, 'common', 2950),
            $c('30700', '장기임대보증금', 'liability', 'long_term_liability', '22', 3, 'common', 3070),

            // ============================================================
            // 자본 (Capital)
            // ============================================================
            $c('3', '자본', 'capital', null, null, 1, 'common', 300),

            // -- 자본금 --
            $c('31', '자본금', 'capital', 'capital', '3', 2, 'common', 310),
            $c('33100', '자본금', 'capital', 'capital', '31', 3, 'common', 3310),
            $c('33200', '우선주자본금', 'capital', 'capital', '31', 3, 'common', 3320),

            // -- 잉여금 --
            $c('32', '잉여금', 'capital', 'capital', '3', 2, 'common', 320),
            $c('34100', '주식발행초과금', 'capital', 'capital', '32', 3, 'common', 3410),
            $c('35100', '이익준비금', 'capital', 'capital', '32', 3, 'common', 3510),
            $c('37500', '이월이익잉여금', 'capital', 'capital', '32', 3, 'common', 3750),
            $c('37900', '당기순이익', 'capital', 'capital', '32', 3, 'common', 3790),

            // ============================================================
            // 수익 (Revenue)
            // ============================================================
            $c('4', '수익', 'revenue', null, null, 1, 'common', 400),

            // -- 매출 --
            $c('41', '매출', 'revenue', 'sales_revenue', '4', 2, 'common', 410),
            $c('40100', '상품매출', 'revenue', 'sales_revenue', '41', 3, 'common', 4010),
            $c('40400', '제품매출', 'revenue', 'sales_revenue', '41', 3, 'common', 4040),
            $c('40700', '공사수입금', 'revenue', 'sales_revenue', '41', 3, 'common', 4070),
            $c('41000', '임대료수입', 'revenue', 'sales_revenue', '41', 3, 'common', 4100),

            // -- 영업외수익 --
            $c('42', '영업외수익', 'revenue', 'other_revenue', '4', 2, 'common', 420),
            $c('90100', '이자수익', 'revenue', 'other_revenue', '42', 3, 'common', 9010),
            $c('90300', '배당금수익', 'revenue', 'other_revenue', '42', 3, 'common', 9030),
            $c('90400', '수입임대료', 'revenue', 'other_revenue', '42', 3, 'common', 9040),
            $c('90700', '외환차익', 'revenue', 'other_revenue', '42', 3, 'common', 9070),
            $c('93000', '잡이익', 'revenue', 'other_revenue', '42', 3, 'common', 9300),

            // ============================================================
            // 비용 (Expenses)
            // ============================================================
            $c('5', '비용', 'expense', null, null, 1, 'common', 500),

            // -- 매출원가/제조원가 (제조부문) --
            $c('51', '매출원가', 'expense', 'cogs', '5', 2, 'manufacturing', 510),
            $c('50100', '원재료비', 'expense', 'cogs', '51', 3, 'manufacturing', 5010),
            $c('50200', '외주가공비', 'expense', 'cogs', '51', 3, 'manufacturing', 5020),
            $c('50300', '급여(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5030),
            $c('50400', '임금', 'expense', 'cogs', '51', 3, 'manufacturing', 5040),
            $c('50500', '상여금(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5050),
            $c('50800', '퇴직급여(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5080),
            $c('51100', '복리후생비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5110),
            $c('51200', '여비교통비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5120),
            $c('51300', '접대비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5130),
            $c('51400', '통신비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5140),
            $c('51600', '전력비', 'expense', 'cogs', '51', 3, 'manufacturing', 5160),
            $c('51700', '세금과공과금(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5170),
            $c('51800', '감가상각비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5180),
            $c('51900', '지급임차료(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5190),
            $c('52000', '수선비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5200),
            $c('52100', '보험료(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5210),
            $c('52200', '차량유지비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5220),
            $c('52400', '운반비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5240),
            $c('53000', '소모품비(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5300),
            $c('53100', '지급수수료(제조)', 'expense', 'cogs', '51', 3, 'manufacturing', 5310),

            // -- 판매비와관리비 (관리부문) --
            $c('52', '판매비와관리비', 'expense', 'selling_admin', '5', 2, 'admin', 520),
            $c('80100', '임원급여', 'expense', 'selling_admin', '52', 3, 'admin', 8010),
            $c('80200', '직원급여', 'expense', 'selling_admin', '52', 3, 'admin', 8020),
            $c('80300', '상여금', 'expense', 'selling_admin', '52', 3, 'admin', 8030),
            $c('80600', '퇴직급여', 'expense', 'selling_admin', '52', 3, 'admin', 8060),
            $c('81100', '복리후생비', 'expense', 'selling_admin', '52', 3, 'admin', 8110),
            $c('81200', '여비교통비', 'expense', 'selling_admin', '52', 3, 'admin', 8120),
            $c('81300', '접대비', 'expense', 'selling_admin', '52', 3, 'admin', 8130),
            $c('81400', '통신비', 'expense', 'selling_admin', '52', 3, 'admin', 8140),
            $c('81500', '수도광열비', 'expense', 'selling_admin', '52', 3, 'admin', 8150),
            $c('81700', '세금과공과금', 'expense', 'selling_admin', '52', 3, 'admin', 8170),
            $c('81800', '감가상각비', 'expense', 'selling_admin', '52', 3, 'admin', 8180),
            $c('81900', '지급임차료', 'expense', 'selling_admin', '52', 3, 'admin', 8190),
            $c('82000', '수선비', 'expense', 'selling_admin', '52', 3, 'admin', 8200),
            $c('82100', '보험료', 'expense', 'selling_admin', '52', 3, 'admin', 8210),
            $c('82200', '차량유지비', 'expense', 'selling_admin', '52', 3, 'admin', 8220),
            $c('82300', '경상연구개발비', 'expense', 'selling_admin', '52', 3, 'admin', 8230),
            $c('82400', '운반비', 'expense', 'selling_admin', '52', 3, 'admin', 8240),
            $c('82500', '교육훈련비', 'expense', 'selling_admin', '52', 3, 'admin', 8250),
            $c('82600', '도서인쇄비', 'expense', 'selling_admin', '52', 3, 'admin', 8260),
            $c('82700', '회의비', 'expense', 'selling_admin', '52', 3, 'admin', 8270),
            $c('82900', '사무용품비', 'expense', 'selling_admin', '52', 3, 'admin', 8290),
            $c('83000', '소모품비', 'expense', 'selling_admin', '52', 3, 'admin', 8300),
            $c('83100', '지급수수료', 'expense', 'selling_admin', '52', 3, 'admin', 8310),
            $c('83200', '보관료', 'expense', 'selling_admin', '52', 3, 'admin', 8320),
            $c('83300', '광고선전비', 'expense', 'selling_admin', '52', 3, 'admin', 8330),
            $c('83500', '대손상각비', 'expense', 'selling_admin', '52', 3, 'admin', 8350),
            $c('84800', '잡비', 'expense', 'selling_admin', '52', 3, 'admin', 8480),

            // -- 영업외비용 --
            $c('53', '영업외비용', 'expense', 'other_expense', '5', 2, 'common', 530),
            $c('93100', '이자비용', 'expense', 'other_expense', '53', 3, 'common', 9310),
            $c('93200', '외환차손', 'expense', 'other_expense', '53', 3, 'common', 9320),
            $c('93300', '기부금', 'expense', 'other_expense', '53', 3, 'common', 9330),
            $c('96000', '잡손실', 'expense', 'other_expense', '53', 3, 'common', 9600),
            $c('99800', '법인세', 'expense', 'other_expense', '53', 3, 'common', 9980),
            $c('99900', '소득세등', 'expense', 'other_expense', '53', 3, 'common', 9990),
        ];
    }
}
