<?php

namespace Modules\PortalApi\Console;

use Illuminate\Console\Command;
use Modules\PortalApi\Services\PwaBuilder;

/**
 * Canonical rebuild of the pet-owner PWA.
 *
 *   php artisan portal:build-pwa
 *
 * Always builds  pwa-owner/  →  public/app/  (safe temp-then-swap). This is the
 * supported way to deploy the PWA; do NOT run `npm run build` from a copied or
 * stale pwa-owner folder, which is what made the app "revert to old".
 */
class BuildPwaCommand extends Command
{
    protected $signature   = 'portal:build-pwa';
    protected $description = 'Rebuild the pet-owner PWA from pwa-owner/ into public/app (safe temp-then-swap)';

    public function handle(): int
    {
        $this->info('Building the pet-owner PWA from pwa-owner/ → public/app …');

        $result = PwaBuilder::build();

        if (! empty($result['output'])) {
            $this->newLine();
            $this->line($result['output']);
        }

        $this->newLine();
        if ($result['ok']) {
            $this->info("✓ PWA rebuilt successfully" . (isset($result['duration']) ? " in {$result['duration']}s." : '.'));
            return self::SUCCESS;
        }

        $this->error('✗ PWA build failed.');
        if (! empty($result['hint'])) {
            $this->warn($result['hint']);
        }
        return self::FAILURE;
    }
}
