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

#nullable disable

namespace TakeoutSaaS.Infrastructure.Migrations.IdentityDb;

/// <summary>
/// 写入财务概览菜单与权限定义。
/// </summary>
[DbContext(typeof(IdentityDbContext))]
[Migration("20260305110000_SeedFinanceOverviewMenuAndPermissions")]
public sealed class SeedFinanceOverviewMenuAndPermissions : Migration
{
    /// <inheritdoc />
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(
            """
            DO $$
            DECLARE
                v_parent_permission_id bigint;
                v_view_permission_id bigint;
                v_parent_menu_id bigint;
                v_overview_menu_id bigint;
                v_permission_seed_base bigint := 840300000000000000;
                v_menu_seed_base bigint := 850300000000000000;
            BEGIN
                -- 1. 确保财务权限分组存在。
                SELECT "Id"
                INTO v_parent_permission_id
                FROM public.permissions
                WHERE "Code" = 'group:tenant:finance'
                ORDER BY "Id"
                LIMIT 1;

                IF v_parent_permission_id IS NULL THEN
                    v_parent_permission_id := v_permission_seed_base + 1;
                    INSERT INTO public.permissions (
                        "Id", "Name", "Code", "Description",
                        "CreatedAt", "UpdatedAt", "DeletedAt",
                        "CreatedBy", "UpdatedBy", "DeletedBy",
                        "ParentId", "SortOrder", "Type", "Portal")
                    VALUES (
                        v_parent_permission_id, '财务中心', 'group:tenant:finance', '财务中心权限分组',
                        NOW(), NULL, NULL,
                        NULL, NULL, NULL,
                        0, 5000, 'group', 1)
                    ON CONFLICT ("Code") DO NOTHING;
                END IF;

                -- 2. Upsert 财务概览查看权限。
                INSERT INTO public.permissions (
                    "Id", "Name", "Code", "Description",
                    "CreatedAt", "UpdatedAt", "DeletedAt",
                    "CreatedBy", "UpdatedBy", "DeletedBy",
                    "ParentId", "SortOrder", "Type", "Portal")
                VALUES (
                    v_permission_seed_base + 11, '财务概览查看', 'tenant:finance:overview:view', '查看财务概览驾驶舱',
                    NOW(), NULL, NULL,
                    NULL, NULL, NULL,
                    v_parent_permission_id, 5050, 'leaf', 1)
                ON CONFLICT ("Code") DO UPDATE
                SET "Name" = EXCLUDED."Name",
                    "Description" = EXCLUDED."Description",
                    "ParentId" = EXCLUDED."ParentId",
                    "SortOrder" = EXCLUDED."SortOrder",
                    "Type" = EXCLUDED."Type",
                    "Portal" = EXCLUDED."Portal",
                    "DeletedAt" = NULL,
                    "DeletedBy" = NULL,
                    "UpdatedAt" = NOW();

                SELECT "Id" INTO v_view_permission_id
                FROM public.permissions
                WHERE "Code" = 'tenant:finance:overview:view'
                LIMIT 1;

                -- 3. 确保租户端财务父菜单存在。
                SELECT "Id"
                INTO v_parent_menu_id
                FROM public.menu_definitions
                WHERE "Portal" = 1 AND "Path" = '/finance' AND "DeletedAt" IS NULL
                ORDER BY "Id"
                LIMIT 1;

                IF v_parent_menu_id IS NULL THEN
                    v_parent_menu_id := v_menu_seed_base + 1;
                    INSERT INTO public.menu_definitions (
                        "Id", "ParentId", "Name", "Path", "Component", "Title", "Icon",
                        "IsIframe", "Link", "KeepAlive", "SortOrder",
                        "RequiredPermissions", "MetaPermissions", "MetaRoles", "AuthListJson",
                        "CreatedAt", "UpdatedAt", "DeletedAt", "CreatedBy", "UpdatedBy", "DeletedBy", "Portal")
                    VALUES (
                        v_parent_menu_id, 0, 'Finance', '/finance', 'BasicLayout', '财务中心', 'lucide:wallet',
                        FALSE, NULL, FALSE, 500,
                        '', '', '', NULL,
                        NOW(), NULL, NULL, NULL, NULL, NULL, 1)
                    ON CONFLICT ("Id") DO NOTHING;
                END IF;

                -- 4. Upsert 财务概览菜单。
                SELECT "Id"
                INTO v_overview_menu_id
                FROM public.menu_definitions
                WHERE "Portal" = 1
                  AND ("Path" = '/finance/overview' OR ("Path" = 'overview' AND "Component" = '/finance/overview/index'))
                ORDER BY "DeletedAt" NULLS FIRST, "Id"
                LIMIT 1;

                IF v_overview_menu_id IS NULL THEN
                    v_overview_menu_id := v_menu_seed_base + 11;
                    INSERT INTO public.menu_definitions (
                        "Id", "ParentId", "Name", "Path", "Component", "Title", "Icon",
                        "IsIframe", "Link", "KeepAlive", "SortOrder",
                        "RequiredPermissions", "MetaPermissions", "MetaRoles", "AuthListJson",
                        "CreatedAt", "UpdatedAt", "DeletedAt", "CreatedBy", "UpdatedBy", "DeletedBy", "Portal")
                    VALUES (
                        v_overview_menu_id, v_parent_menu_id, 'FinanceOverview', '/finance/overview', '/finance/overview/index', '财务概览', 'lucide:layout-dashboard',
                        FALSE, NULL, TRUE, 505,
                        'tenant:finance:overview:view', 'tenant:finance:overview:view', '', NULL,
                        NOW(), NULL, NULL, NULL, NULL, NULL, 1)
                    ON CONFLICT ("Id") DO NOTHING;
                ELSE
                    UPDATE public.menu_definitions
                    SET "ParentId" = v_parent_menu_id,
                        "Name" = 'FinanceOverview',
                        "Path" = '/finance/overview',
                        "Component" = '/finance/overview/index',
                        "Title" = '财务概览',
                        "Icon" = 'lucide:layout-dashboard',
                        "IsIframe" = FALSE,
                        "Link" = NULL,
                        "KeepAlive" = TRUE,
                        "SortOrder" = 505,
                        "RequiredPermissions" = 'tenant:finance:overview:view',
                        "MetaPermissions" = 'tenant:finance:overview:view',
                        "MetaRoles" = '',
                        "DeletedAt" = NULL,
                        "DeletedBy" = NULL,
                        "UpdatedAt" = NOW(),
                        "Portal" = 1
                    WHERE "Id" = v_overview_menu_id;
                END IF;

                -- 5. 为 tenant-admin 角色授予权限。
                INSERT INTO public.role_permissions (
                    "Id", "RoleId", "PermissionId", "CreatedAt", "UpdatedAt", "DeletedAt",
                    "CreatedBy", "UpdatedBy", "DeletedBy", "TenantId", "Portal")
                SELECT
                    ABS(HASHTEXTEXTENDED('tenant-admin:overview:' || role."Id"::text || ':' || v_view_permission_id::text, 0)),
                    role."Id",
                    v_view_permission_id,
                    NOW(), NULL, NULL,
                    NULL, NULL, NULL,
                    role."TenantId",
                    1
                FROM public.roles role
                WHERE role."Code" = 'tenant-admin'
                  AND role."DeletedAt" IS NULL
                  AND v_view_permission_id IS NOT NULL
                ON CONFLICT ("RoleId", "PermissionId") DO UPDATE
                SET "DeletedAt" = NULL,
                    "DeletedBy" = NULL,
                    "UpdatedAt" = NOW(),
                    "Portal" = 1;

                -- 6. 为 tenant-admin 角色模板授予权限。
                INSERT INTO public.role_template_permissions (
                    "Id", "RoleTemplateId", "PermissionCode",
                    "CreatedAt", "UpdatedAt", "DeletedAt",
                    "CreatedBy", "UpdatedBy", "DeletedBy")
                SELECT
                    ABS(HASHTEXTEXTENDED('template-overview:' || template."Id"::text || ':tenant:finance:overview:view', 0)),
                    template."Id",
                    'tenant:finance:overview:view',
                    NOW(), NULL, NULL,
                    NULL, NULL, NULL
                FROM public.role_templates template
                WHERE template."TemplateCode" = 'tenant-admin'
                  AND template."DeletedAt" IS NULL
                ON CONFLICT ("RoleTemplateId", "PermissionCode") DO UPDATE
                SET "DeletedAt" = NULL,
                    "DeletedBy" = NULL,
                    "UpdatedAt" = NOW();
            END $$;
            """);
    }

    /// <inheritdoc />
    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(
            """
            DO $$
            BEGIN
                DELETE FROM public.role_permissions
                WHERE "PermissionId" IN (
                    SELECT "Id"
                    FROM public.permissions
                    WHERE "Code" = 'tenant:finance:overview:view');

                DELETE FROM public.role_template_permissions
                WHERE "PermissionCode" = 'tenant:finance:overview:view';

                DELETE FROM public.menu_definitions
                WHERE "Portal" = 1 AND "Path" = '/finance/overview';

                DELETE FROM public.permissions
                WHERE "Code" = 'tenant:finance:overview:view';
            END $$;
            """);
    }
}
