<?php

declare(strict_types=1);

namespace App\Framework\Database\Schema;

/**
 * Materialized View Definition für PostgreSQL
 *
 * Materialized Views sind Views mit physisch gespeicherten Ergebnissen:
 * - Schneller als normale Views (keine Re-Computation)
 * - Unterstützen Indexes
 * - Müssen manuell oder geplant refreshed werden
 */
final readonly class MaterializedView
{
    public function __construct(
        public string $name,
        public string $query,
        public bool $withData = true
    ) {}

    /**
     * Generiert CREATE MATERIALIZED VIEW SQL
     */
    public function toSql(): string
    {
        $sql = "CREATE MATERIALIZED VIEW \"{$this->name}\" AS {$this->query}";

        if (!$this->withData) {
            $sql .= " WITH NO DATA";
        }

        return $sql;
    }

    /**
     * Generiert REFRESH MATERIALIZED VIEW SQL
     */
    public function refreshSql(bool $concurrently = false): string
    {
        $sql = "REFRESH MATERIALIZED VIEW";

        if ($concurrently) {
            $sql .= " CONCURRENTLY";
        }

        $sql .= " \"{$this->name}\"";

        return $sql;
    }

    /**
     * Generiert DROP MATERIALIZED VIEW SQL
     */
    public function dropSql(bool $ifExists = false): string
    {
        $sql = "DROP MATERIALIZED VIEW";

        if ($ifExists) {
            $sql .= " IF EXISTS";
        }

        $sql .= " \"{$this->name}\"";

        return $sql;
    }
}
