using System;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Tiku.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    public partial class AddPlatformGovernanceCenters : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "platform_configuration_definitions",
                columns: table => new
                {
                    id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
                    code = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
                    name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
                    category = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
                    value_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
                    allow_runtime_management = table.Column<bool>(type: "boolean", nullable: false),
                    is_sensitive = table.Column<bool>(type: "boolean", nullable: false),
                    description = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: true),
                    validation_schema = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
                    created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
                    updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
                },
                constraints: table =>
                {
                    table.PrimaryKey("pk_platform_configuration_definitions", x => x.id);
                });

            migrationBuilder.CreateTable(
                name: "platform_notification_templates",
                columns: table => new
                {
                    id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
                    code = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
                    name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
                    channel = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
                    subject_template = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
                    body_template = table.Column<string>(type: "character varying(8000)", maxLength: 8000, nullable: false),
                    enabled = table.Column<bool>(type: "boolean", nullable: false),
                    variables = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'[]'::jsonb"),
                    created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
                    updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
                },
                constraints: table =>
                {
                    table.PrimaryKey("pk_platform_notification_templates", x => x.id);
                });

            migrationBuilder.CreateTable(
                name: "platform_configuration_versions",
                columns: table => new
                {
                    id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
                    definition_id = table.Column<Guid>(type: "uuid", nullable: false),
                    environment = table.Column<string>(type: "character varying(80)", maxLength: 80, nullable: false),
                    version = table.Column<int>(type: "integer", nullable: false),
                    status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
                    value = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
                    secret_ref = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: true),
                    created_by = table.Column<Guid>(type: "uuid", nullable: false),
                    published_by = table.Column<Guid>(type: "uuid", nullable: true),
                    rolled_back_from_version_id = table.Column<Guid>(type: "uuid", nullable: true),
                    reason = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: false),
                    published_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
                    created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
                    updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
                },
                constraints: table =>
                {
                    table.PrimaryKey("pk_platform_configuration_versions", x => x.id);
                    table.ForeignKey(
                        name: "fk_platform_configuration_versions_platform_configuration_defi~",
                        column: x => x.definition_id,
                        principalTable: "platform_configuration_definitions",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "fk_platform_configuration_versions_platform_configuration_vers~",
                        column: x => x.rolled_back_from_version_id,
                        principalTable: "platform_configuration_versions",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "fk_platform_configuration_versions_users_created_by",
                        column: x => x.created_by,
                        principalTable: "users",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "fk_platform_configuration_versions_users_published_by",
                        column: x => x.published_by,
                        principalTable: "users",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "platform_notification_deliveries",
                columns: table => new
                {
                    id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
                    template_id = table.Column<Guid>(type: "uuid", nullable: false),
                    recipient_user_id = table.Column<Guid>(type: "uuid", nullable: false),
                    recipient_role_code = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
                    channel = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
                    status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
                    subject = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
                    body = table.Column<string>(type: "character varying(8000)", maxLength: 8000, nullable: false),
                    idempotency_key = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
                    attempts = table.Column<int>(type: "integer", nullable: false),
                    last_error = table.Column<string>(type: "character varying(4000)", maxLength: 4000, nullable: true),
                    sent_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
                    created_by = table.Column<Guid>(type: "uuid", nullable: false),
                    metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
                    created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
                    updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
                },
                constraints: table =>
                {
                    table.PrimaryKey("pk_platform_notification_deliveries", x => x.id);
                    table.ForeignKey(
                        name: "fk_platform_notification_deliveries_platform_notification_temp~",
                        column: x => x.template_id,
                        principalTable: "platform_notification_templates",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "fk_platform_notification_deliveries_users_created_by",
                        column: x => x.created_by,
                        principalTable: "users",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "fk_platform_notification_deliveries_users_recipient_user_id",
                        column: x => x.recipient_user_id,
                        principalTable: "users",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateIndex(
                name: "ix_platform_configuration_definitions_category_code",
                table: "platform_configuration_definitions",
                columns: new[] { "category", "code" });

            migrationBuilder.CreateIndex(
                name: "ix_platform_configuration_definitions_code",
                table: "platform_configuration_definitions",
                column: "code",
                unique: true);

            migrationBuilder.CreateIndex(
                name: "ix_platform_configuration_versions_created_by",
                table: "platform_configuration_versions",
                column: "created_by");

            migrationBuilder.CreateIndex(
                name: "ix_platform_configuration_versions_definition_id_environment_s~",
                table: "platform_configuration_versions",
                columns: new[] { "definition_id", "environment", "status" });

            migrationBuilder.CreateIndex(
                name: "ix_platform_configuration_versions_definition_id_environment_v~",
                table: "platform_configuration_versions",
                columns: new[] { "definition_id", "environment", "version" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "ix_platform_configuration_versions_published_by",
                table: "platform_configuration_versions",
                column: "published_by");

            migrationBuilder.CreateIndex(
                name: "ix_platform_configuration_versions_rolled_back_from_version_id",
                table: "platform_configuration_versions",
                column: "rolled_back_from_version_id");

            migrationBuilder.CreateIndex(
                name: "ix_platform_notification_deliveries_created_by",
                table: "platform_notification_deliveries",
                column: "created_by");

            migrationBuilder.CreateIndex(
                name: "ix_platform_notification_deliveries_recipient_user_id",
                table: "platform_notification_deliveries",
                column: "recipient_user_id");

            migrationBuilder.CreateIndex(
                name: "ix_platform_notification_deliveries_status_created_at",
                table: "platform_notification_deliveries",
                columns: new[] { "status", "created_at" });

            migrationBuilder.CreateIndex(
                name: "ix_platform_notification_deliveries_template_id_recipient_user~",
                table: "platform_notification_deliveries",
                columns: new[] { "template_id", "recipient_user_id", "idempotency_key" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "ix_platform_notification_templates_code",
                table: "platform_notification_templates",
                column: "code",
                unique: true);

            migrationBuilder.Sql("""
                UPDATE backend_menus
                SET path = CASE code
                    WHEN 'platform.dashboard' THEN '/'
                    WHEN 'platform.tenants' THEN '/tenants'
                    WHEN 'platform.staff' THEN '/staff'
                    WHEN 'platform.content' THEN '/question-banks'
                    WHEN 'platform.audit' THEN '/audit'
                    WHEN 'platform.crm' THEN '/crm'
                    WHEN 'platform.sms' THEN '/sms'
                    WHEN 'platform.payment' THEN '/payments'
                    ELSE path
                END
                WHERE (code, path) IN (
                    ('platform.dashboard', '/platform/dashboard'),
                    ('platform.tenants', '/platform/tenants'),
                    ('platform.staff', '/platform/staff'),
                    ('platform.content', '/platform/question-banks'),
                    ('platform.audit', '/platform/audit'),
                    ('platform.crm', '/platform/crm'),
                    ('platform.sms', '/platform/sms'),
                    ('platform.payment', '/platform/payment-settings'));

                UPDATE backend_menus
                SET is_active = FALSE
                WHERE code = 'platform.saas' AND path = '/platform/saas';
                """);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "platform_configuration_versions");

            migrationBuilder.DropTable(
                name: "platform_notification_deliveries");

            migrationBuilder.DropTable(
                name: "platform_configuration_definitions");

            migrationBuilder.DropTable(
                name: "platform_notification_templates");
        }
    }
}
