using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using TakeoutSaaS.Infrastructure.App.Persistence;

#nullable disable

namespace TakeoutSaaS.Infrastructure.Migrations
{
    /// <inheritdoc />
    [DbContext(typeof(TakeoutAppDbContext))]
    [Migration("20251225090000_AddTenantAnnouncementRowVersionTrigger")]
    public partial class AddTenantAnnouncementRowVersionTrigger : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(
                """
                CREATE OR REPLACE FUNCTION public.set_tenant_announcement_row_version()
                RETURNS trigger AS $$
                BEGIN
                    NEW."RowVersion" = decode(md5(random()::text || clock_timestamp()::text), 'hex');
                    RETURN NEW;
                END;
                $$ LANGUAGE plpgsql;
                """);

            migrationBuilder.Sql(
                """
                DROP TRIGGER IF EXISTS trg_tenant_announcements_row_version ON tenant_announcements;
                CREATE TRIGGER trg_tenant_announcements_row_version
                BEFORE INSERT OR UPDATE ON tenant_announcements
                FOR EACH ROW EXECUTE FUNCTION public.set_tenant_announcement_row_version();
                """);

            migrationBuilder.Sql(
                """
                UPDATE tenant_announcements
                SET "RowVersion" = decode(md5(random()::text || clock_timestamp()::text), 'hex')
                WHERE "RowVersion" IS NULL OR octet_length("RowVersion") = 0;
                """);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(
                """
                DROP TRIGGER IF EXISTS trg_tenant_announcements_row_version ON tenant_announcements;
                DROP FUNCTION IF EXISTS public.set_tenant_announcement_row_version();
                """);
        }
    }
}
