<?php

namespace App\Console\Commands;

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

/**
 * One-time backfill: every existing company with AutoCount Sync enabled gets
 * cr6f2_acsynctype = "Cloud". Run after provisioning the new column in
 * Dataverse and before deploying the gated UI.
 *
 *   php artisan dataverse:backfill-acsynctype
 *   php artisan dataverse:backfill-acsynctype --dry-run
 *   php artisan dataverse:backfill-acsynctype --default=Desktop  (override)
 */
class BackfillAcSyncType extends Command
{
    protected $signature = 'dataverse:backfill-acsynctype
                            {--default=Cloud : Value to write (Cloud or Desktop)}
                            {--dry-run : Print what would change, do not write}';

    protected $description = 'Set cr6f2_acsynctype on companies that have AutoCount Sync enabled but no type set.';

    public function handle(DataverseService $dv): int
    {
        $default = $this->option('default');
        $dryRun  = (bool) $this->option('dry-run');

        if (!in_array($default, ['Cloud', 'Desktop'], true)) {
            $this->error("--default must be Cloud or Desktop, got: {$default}");
            return self::FAILURE;
        }

        $this->info("Backfilling cr6f2_acsynctype = {$default} where AutoCount Sync is enabled and type is blank.");
        if ($dryRun) $this->warn('Dry run — no writes will be made.');
        $this->newLine();

        try {
            $rows = $dv->get('cr6f2_companies', [
                'select' => ['cr6f2_companyid', 'cr6f2_name', 'cr6f2_acsyncsupport', 'cr6f2_acsynctype'],
                'filter' => 'cr6f2_acsyncsupport eq true',
                'top'    => 5000,
            ]);
        } catch (Throwable $e) {
            $this->error('Failed to fetch companies: ' . $e->getMessage());
            return self::FAILURE;
        }

        $updated = 0; $skipped = 0; $errors = 0;
        foreach ($rows['value'] ?? [] as $row) {
            $id   = $row['cr6f2_companyid'];
            $name = $row['cr6f2_name'] ?? '(no name)';
            $cur  = $row['cr6f2_acsynctype'] ?? null;

            if ($cur !== null && $cur !== '') {
                $this->line("  <fg=gray>SKIP</> {$name} — already {$cur}");
                $skipped++;
                continue;
            }

            if ($dryRun) {
                $this->line("  <fg=yellow>WOULD</> {$name} → {$default}");
                $updated++;
                continue;
            }

            try {
                $dv->update('cr6f2_companies', $id, ['cr6f2_acsynctype' => $default]);
                $this->line("  <fg=green>SET</>  {$name} → {$default}");
                $updated++;
            } catch (Throwable $e) {
                $this->line("  <fg=red>FAIL</> {$name} — " . $e->getMessage());
                $errors++;
            }
        }

        $this->newLine();
        $this->info("Done. {$updated} updated, {$skipped} skipped, {$errors} errors.");
        return $errors > 0 ? self::FAILURE : self::SUCCESS;
    }
}
