<?php

namespace App\Modules\FINANCE\Services;

use App\Modules\FINANCE\Models\Invoice;
use App\Modules\FINANCE\Models\CreditNote;
use Illuminate\Support\Facades\DB;

class CreditNoteService
{
    /**
     * Create a credit note and optionally adjust invoice balance.
     */
    public function createCreditNote(array $data): CreditNote
    {
        return DB::transaction(function () use ($data) {
            $creditNote = CreditNote::create([
                'company_id' => $data['company_id'],
                'invoice_id' => $data['invoice_id'] ?? null,
                'client_id' => $data['client_id'],
                'amount' => $data['amount'],
                'reason' => $data['reason'] ?? null,
                'status' => 'active',
            ]);

            // If linked to an invoice, adjust the balance
            if (isset($data['invoice_id'])) {
                $invoice = Invoice::findOrFail($data['invoice_id']);
                
                // We treat credit note as a form of "payment" or reduction in balance
                $newBalanceAmount = $invoice->balance_amount - $creditNote->amount;
                
                $status = $invoice->status;
                if ($newBalanceAmount <= 0) {
                    $status = 'paid';
                }

                $invoice->update([
                    'balance_amount' => max(0, $newBalanceAmount),
                    'status' => $status,
                ]);
            }

            return $creditNote;
        });
    }
}
