<?php

namespace App\Console\Commands;

use App\Services\DataverseService;
use Illuminate\Console\Command;
use Throwable;

/**
 * One-time seeder: writes the full Singapore GST rate history to every
 * SG_GST standard-rated tax code that does not yet have history set.
 *
 * Default: dry run. Pass --apply to write to Dataverse.
 */
class SeedSgGstRateHistory extends Command
{
    protected $signature = 'tax:seed-sg-history
                            {--apply : Actually write to Dataverse (default: dry run)}';

    protected $description = 'Seed Singapore GST rate history on SG_GST standard-rated tax codes';

    /** Full SG GST rate history, descending by start_date. */
    private const HISTORY = [
        ['start_date' => '2024-01-01', 'rate' => 9],
        ['start_date' => '2023-01-01', 'rate' => 8],
        ['start_date' => '2007-07-01', 'rate' => 7],
        ['start_date' => '2004-01-01', 'rate' => 5],
        ['start_date' => '2003-01-01', 'rate' => 4],
        ['start_date' => '1994-04-01', 'rate' => 3],
    ];

    public function handle(DataverseService $dv): int
    {
        $apply = (bool) $this->option('apply');

        $this->line('  <fg=cyan>Mode:</> ' . ($apply ? 'APPLY' : 'dry run'));
        $this->newLine();

        try {
            $result = $dv->get('cr6f2_taxcodes', [
                'select' => ['cr6f2_taxcodeid', 'cr6f2_taxcodeidentifier', 'cr6f2_taxratepercentage', 'cr6f2_taxratehistory'],
                'filter' => "cr6f2_taxsystem eq 'SG_GST'",
                'top'    => 200,
            ]);
        } catch (Throwable $e) {
            $this->error('Failed to fetch tax codes: ' . $e->getMessage());
            return Command::FAILURE;
        }

        $codes = $result['value'] ?? [];

        if (empty($codes)) {
            $this->warn('No SG_GST tax codes found.');
            return Command::SUCCESS;
        }

        $toWrite  = 0;
        $skipped  = 0;
        $written  = 0;

        foreach ($codes as $tc) {
            $code = $tc['cr6f2_taxcodeidentifier'] ?? '(unknown)';
            $rate = $tc['cr6f2_taxratepercentage']  ?? null;

            // Only seed standard-rated codes (rate > 0)
            if ($rate === null || (float) $rate <= 0) {
                $this->line("  <fg=gray>·</> {$code} rate={$rate}% — zero/exempt, skipped");
                $skipped++;
                continue;
            }

            // Skip if history already set
            if (!empty($tc['cr6f2_taxratehistory'])) {
                $this->line("  <fg=gray>·</> {$code} — already has history, skipped");
                $skipped++;
                continue;
            }

            $toWrite++;

            if (!$apply) {
                $this->line("  <fg=green>+</> {$code} — would write 6-entry history");
                continue;
            }

            try {
                $dv->update('cr6f2_taxcodes', $tc['cr6f2_taxcodeid'], [
                    'cr6f2_taxratehistory' => json_encode(self::HISTORY),
                ]);
                $this->line("  <fg=green>✓</> {$code} — history written");
                $written++;
            } catch (Throwable $e) {
                $this->error("  ✗ {$code}: " . $e->getMessage());
                return Command::FAILURE;
            }
        }

        $this->newLine();

        if ($apply) {
            $this->info("Done. Written: {$written}, skipped: {$skipped}.");
        } else {
            $this->info("Dry run complete. {$toWrite} would be written, {$skipped} skipped.");
            $this->line('Re-run with <fg=yellow>--apply</> to write.');
        }

        return Command::SUCCESS;
    }
}
