<?php

namespace App\Models\Barobill;

use App\Models\Tenants\Tenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 홈택스 세금계산서 분개 모델
 * 하나의 세금계산서를 여러 계정과목으로 분개하여 저장
 */
class HometaxInvoiceJournal extends Model
{
    protected $table = 'hometax_invoice_journals';

    protected $fillable = [
        'tenant_id',
        'hometax_invoice_id',
        'nts_confirm_num',
        'dc_type',
        'account_code',
        'account_name',
        'debit_amount',
        'credit_amount',
        'description',
        'sort_order',
        'invoice_type',
        'write_date',
        'supply_amount',
        'tax_amount',
        'total_amount',
        'trading_partner_name',
    ];

    protected $casts = [
        'debit_amount' => 'integer',
        'credit_amount' => 'integer',
        'supply_amount' => 'integer',
        'tax_amount' => 'integer',
        'total_amount' => 'integer',
        'sort_order' => 'integer',
        'write_date' => 'date',
    ];

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    public function invoice(): BelongsTo
    {
        return $this->belongsTo(HometaxInvoice::class, 'hometax_invoice_id');
    }

    /**
     * 특정 인보이스의 분개 저장 (DELETE 후 INSERT)
     */
    public static function saveJournals(int $tenantId, int $invoiceId, array $invoiceData, array $lines): void
    {
        // 기존 분개 삭제
        self::where('tenant_id', $tenantId)
            ->where('hometax_invoice_id', $invoiceId)
            ->delete();

        // 새 분개 저장
        foreach ($lines as $index => $line) {
            self::create([
                'tenant_id' => $tenantId,
                'hometax_invoice_id' => $invoiceId,
                'nts_confirm_num' => $invoiceData['nts_confirm_num'] ?? '',
                'dc_type' => $line['dc_type'],
                'account_code' => $line['account_code'],
                'account_name' => $line['account_name'],
                'debit_amount' => (int) ($line['debit_amount'] ?? 0),
                'credit_amount' => (int) ($line['credit_amount'] ?? 0),
                'description' => $line['description'] ?? '',
                'sort_order' => $index,
                'invoice_type' => $invoiceData['invoice_type'] ?? '',
                'write_date' => $invoiceData['write_date'] ?? null,
                'supply_amount' => (int) ($invoiceData['supply_amount'] ?? 0),
                'tax_amount' => (int) ($invoiceData['tax_amount'] ?? 0),
                'total_amount' => (int) ($invoiceData['total_amount'] ?? 0),
                'trading_partner_name' => $invoiceData['trading_partner_name'] ?? '',
            ]);
        }
    }

    /**
     * 특정 인보이스의 분개 조회
     */
    public static function getByInvoiceId(int $tenantId, int $invoiceId): \Illuminate\Database\Eloquent\Collection
    {
        return self::where('tenant_id', $tenantId)
            ->where('hometax_invoice_id', $invoiceId)
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * 특정 인보이스의 분개 삭제
     */
    public static function deleteJournals(int $tenantId, int $invoiceId): int
    {
        return self::where('tenant_id', $tenantId)
            ->where('hometax_invoice_id', $invoiceId)
            ->delete();
    }

    /**
     * 분개 완료된 인보이스 ID 목록 일괄 조회
     */
    public static function getJournaledInvoiceIds(int $tenantId, array $invoiceIds): array
    {
        if (empty($invoiceIds)) {
            return [];
        }

        return self::where('tenant_id', $tenantId)
            ->whereIn('hometax_invoice_id', $invoiceIds)
            ->distinct()
            ->pluck('hometax_invoice_id')
            ->toArray();
    }
}
