<?php

namespace Database\Seeders;

use App\Models\Company;
use App\Models\CreditNote;
use App\Models\CreditNoteItem;
use App\Models\Invoice;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class CreditNoteSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Demo sales returns (credit notes) for Reports → Sales → Sales Return tab.
     */
    public function run(): void
    {
        $invoices = Invoice::query()->with('customer')->orderBy('id')->take(5)->get();

        if ($invoices->isEmpty()) {
            $this->command->warn('CreditNoteSeeder skipped: no invoices. Run InvoiceSeeder first.');

            return;
        }

        $companyId = Company::query()->value('id');
        $userId = User::query()->value('id');

        $demos = [
            ['suffix' => '000001', 'status' => 'approved', 'daysAgo' => 2],
            ['suffix' => '000002', 'status' => 'pending', 'daysAgo' => 5],
            ['suffix' => '000003', 'status' => 'approved', 'daysAgo' => 10],
            ['suffix' => '000004', 'status' => 'rejected', 'daysAgo' => 14],
            ['suffix' => '000005', 'status' => 'pending', 'daysAgo' => 18],
        ];

        $count = 0;

        foreach ($invoices->values() as $index => $invoice) {
            if (! isset($demos[$index])) {
                break;
            }

            $cfg = $demos[$index];
            $number = 'CN-DEMO-'.$cfg['suffix'];
            $date = Carbon::now()->subDays($cfg['daysAgo'])->startOfDay();

            $rate = round(max(50.0, (float) $invoice->total * 0.12), 2);
            $quantity = 1;
            $itemSubtotal = $rate * $quantity;
            $itemDiscount = 0.0;
            $taxRate = 10.0;
            $itemTax = round(($itemSubtotal - $itemDiscount) * ($taxRate / 100), 2);
            $itemAmount = round($itemSubtotal - $itemDiscount + $itemTax, 2);

            $note = CreditNote::updateOrCreate(
                ['credit_note_number' => $number],
                [
                    'invoice_id' => $invoice->id,
                    'customer_id' => $invoice->customer_id,
                    'company_id' => $companyId,
                    'credit_note_date' => $date,
                    'status' => $cfg['status'],
                    'amount' => $itemSubtotal,
                    'tax_amount' => $itemTax,
                    'discount_amount' => $itemDiscount,
                    'total' => $itemAmount,
                    'currency' => $invoice->currency ?? 'USD',
                    'notes' => 'Demo sales return (seeded for reports).',
                    'terms' => null,
                    'signature_type' => 'manual',
                    'created_by' => $userId,
                ]
            );

            CreditNoteItem::query()->where('credit_note_id', $note->id)->delete();
            CreditNoteItem::query()->create([
                'credit_note_id' => $note->id,
                'description' => 'Demo return line — '.($invoice->invoice_number ?? 'invoice'),
                'quantity' => $quantity,
                'rate' => $rate,
                'discount' => $itemDiscount,
                'tax_rate' => $taxRate,
                'tax_amount' => $itemTax,
                'amount' => $itemAmount,
                'sort_order' => 0,
            ]);

            $count++;
        }

        $this->command->info("Seeded {$count} demo credit notes (CN-DEMO-*). Open Reports → Sales → Sales Return to view.");
    }
}
