<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RefreshMaterializedViews extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'reports:refresh-mviews {--concurrently : Use CONCURRENTLY (Postgres 9.4+; requires indexes)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Refresh configured Postgres materialized views for reporting';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $views = (array) config('reports.materialized_views', []);
        if (empty($views)) {
            $this->info('No materialized views configured.');

            return self::SUCCESS;
        }

        $concurrently = $this->option('concurrently') ? ' CONCURRENTLY' : '';

        foreach ($views as $view) {
            $name = trim((string) $view);
            if ($name === '') {
                continue;
            }
            $sql = 'REFRESH MATERIALIZED VIEW'.$concurrently.' '.DB::getPdo()->quote($name);
            // PDO::quote wraps with single quotes; for identifiers we need double quotes or no quotes.
            // Use a safe fallback: wrap with " if not already quoted
            $safe = 'REFRESH MATERIALIZED VIEW'.$concurrently.' "'.str_replace('"', '""', $name).'"';
            try {
                DB::statement($safe);
                $this->info("Refreshed: {$name}");
            } catch (\Throwable $e) {
                $this->error("Failed to refresh {$name}: ".$e->getMessage());
            }
        }

        return self::SUCCESS;
    }
}
