-- ============================================================================
-- 添加系统账户和待解锁算力挖矿功能
-- 1. MiningConfig 添加全网理论算力字段
-- 2. 系统账户（运营/省/市/总部）挖矿
-- 3. 待解锁算力挖矿记录
-- 4. 挖矿收益分配明细
-- ============================================================================

-- ==================== MiningConfig 添加全网理论算力字段 ====================

ALTER TABLE "mining_configs" ADD COLUMN IF NOT EXISTS "network_total_contribution" DECIMAL(30, 8) NOT NULL DEFAULT 0;
ALTER TABLE "mining_configs" ADD COLUMN IF NOT EXISTS "total_tree_count" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "mining_configs" ADD COLUMN IF NOT EXISTS "contribution_per_tree" DECIMAL(20, 10) NOT NULL DEFAULT 22617;
ALTER TABLE "mining_configs" ADD COLUMN IF NOT EXISTS "network_last_synced_at" TIMESTAMP(3);

-- ==================== 系统账户类型枚举 ====================

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'SystemAccountType') THEN
        CREATE TYPE "SystemAccountType" AS ENUM ('OPERATION', 'PROVINCE', 'CITY', 'HEADQUARTERS');
    END IF;
END$$;

-- ==================== 系统挖矿账户 ====================

CREATE TABLE IF NOT EXISTS "system_mining_accounts" (
    "id" TEXT NOT NULL,
    "account_type" "SystemAccountType" NOT NULL,
    "name" VARCHAR(100) NOT NULL,
    "totalMined" DECIMAL(30, 8) NOT NULL DEFAULT 0,
    "availableBalance" DECIMAL(30, 8) NOT NULL DEFAULT 0,
    "totalContribution" DECIMAL(30, 8) NOT NULL DEFAULT 0,
    "last_synced_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "system_mining_accounts_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX IF NOT EXISTS "system_mining_accounts_account_type_key" ON "system_mining_accounts"("account_type");
CREATE INDEX IF NOT EXISTS "system_mining_accounts_totalContribution_idx" ON "system_mining_accounts"("totalContribution" DESC);

-- ==================== 系统账户挖矿记录 ====================

CREATE TABLE IF NOT EXISTS "system_mining_records" (
    "id" TEXT NOT NULL,
    "account_type" "SystemAccountType" NOT NULL,
    "mining_minute" TIMESTAMP(3) NOT NULL,
    "contribution_ratio" DECIMAL(30, 18) NOT NULL,
    "total_contribution" DECIMAL(30, 8) NOT NULL,
    "second_distribution" DECIMAL(30, 18) NOT NULL,
    "mined_amount" DECIMAL(30, 18) NOT NULL,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "system_mining_records_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX IF NOT EXISTS "system_mining_records_account_type_mining_minute_key" ON "system_mining_records"("account_type", "mining_minute");
CREATE INDEX IF NOT EXISTS "system_mining_records_mining_minute_idx" ON "system_mining_records"("mining_minute");

ALTER TABLE "system_mining_records" DROP CONSTRAINT IF EXISTS "system_mining_records_account_type_fkey";
ALTER TABLE "system_mining_records" ADD CONSTRAINT "system_mining_records_account_type_fkey"
    FOREIGN KEY ("account_type") REFERENCES "system_mining_accounts"("account_type") ON DELETE RESTRICT ON UPDATE CASCADE;

-- ==================== 系统账户交易流水 ====================

CREATE TABLE IF NOT EXISTS "system_mining_transactions" (
    "id" TEXT NOT NULL,
    "account_type" "SystemAccountType" NOT NULL,
    "type" TEXT NOT NULL,
    "amount" DECIMAL(30, 8) NOT NULL,
    "balance_before" DECIMAL(30, 8) NOT NULL,
    "balance_after" DECIMAL(30, 8) NOT NULL,
    "reference_id" TEXT,
    "reference_type" TEXT,
    "memo" TEXT,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "system_mining_transactions_pkey" PRIMARY KEY ("id")
);

CREATE INDEX IF NOT EXISTS "system_mining_transactions_account_type_created_at_idx" ON "system_mining_transactions"("account_type", "created_at" DESC);

ALTER TABLE "system_mining_transactions" DROP CONSTRAINT IF EXISTS "system_mining_transactions_account_type_fkey";
ALTER TABLE "system_mining_transactions" ADD CONSTRAINT "system_mining_transactions_account_type_fkey"
    FOREIGN KEY ("account_type") REFERENCES "system_mining_accounts"("account_type") ON DELETE RESTRICT ON UPDATE CASCADE;

-- ==================== 待解锁算力挖矿 ====================

CREATE TABLE IF NOT EXISTS "pending_contribution_mining" (
    "id" BIGSERIAL NOT NULL,
    "source_adoption_id" BIGINT NOT NULL,
    "source_account_sequence" VARCHAR(20) NOT NULL,
    "would_be_account_sequence" VARCHAR(20),
    "contribution_type" VARCHAR(30) NOT NULL,
    "amount" DECIMAL(30, 10) NOT NULL,
    "reason" VARCHAR(200),
    "effective_date" DATE NOT NULL,
    "expire_date" DATE NOT NULL,
    "is_expired" BOOLEAN NOT NULL DEFAULT false,
    "last_synced_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "pending_contribution_mining_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX IF NOT EXISTS "pending_contribution_mining_source_adoption_id_would_be_acco_key"
    ON "pending_contribution_mining"("source_adoption_id", "would_be_account_sequence", "contribution_type");
CREATE INDEX IF NOT EXISTS "pending_contribution_mining_would_be_account_sequence_idx" ON "pending_contribution_mining"("would_be_account_sequence");
CREATE INDEX IF NOT EXISTS "pending_contribution_mining_contribution_type_idx" ON "pending_contribution_mining"("contribution_type");
CREATE INDEX IF NOT EXISTS "pending_contribution_mining_is_expired_idx" ON "pending_contribution_mining"("is_expired");

-- ==================== 待解锁算力挖矿记录 ====================

CREATE TABLE IF NOT EXISTS "pending_mining_records" (
    "id" BIGSERIAL NOT NULL,
    "pending_contribution_id" BIGINT NOT NULL,
    "mining_minute" TIMESTAMP(3) NOT NULL,
    "source_adoption_id" BIGINT NOT NULL,
    "source_account_sequence" VARCHAR(20) NOT NULL,
    "would_be_account_sequence" VARCHAR(20),
    "contribution_type" VARCHAR(30) NOT NULL,
    "contribution_amount" DECIMAL(30, 10) NOT NULL,
    "network_total_contribution" DECIMAL(30, 10) NOT NULL,
    "contribution_ratio" DECIMAL(30, 18) NOT NULL,
    "second_distribution" DECIMAL(30, 18) NOT NULL,
    "mined_amount" DECIMAL(30, 18) NOT NULL,
    "allocated_to" VARCHAR(20) NOT NULL DEFAULT 'HEADQUARTERS',
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "pending_mining_records_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX IF NOT EXISTS "pending_mining_records_pending_contribution_id_mining_minute_key"
    ON "pending_mining_records"("pending_contribution_id", "mining_minute");
CREATE INDEX IF NOT EXISTS "pending_mining_records_mining_minute_idx" ON "pending_mining_records"("mining_minute");
CREATE INDEX IF NOT EXISTS "pending_mining_records_source_account_sequence_idx" ON "pending_mining_records"("source_account_sequence");
CREATE INDEX IF NOT EXISTS "pending_mining_records_would_be_account_sequence_idx" ON "pending_mining_records"("would_be_account_sequence");

ALTER TABLE "pending_mining_records" DROP CONSTRAINT IF EXISTS "pending_mining_records_pending_contribution_id_fkey";
ALTER TABLE "pending_mining_records" ADD CONSTRAINT "pending_mining_records_pending_contribution_id_fkey"
    FOREIGN KEY ("pending_contribution_id") REFERENCES "pending_contribution_mining"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- ==================== 挖矿收益分配明细 ====================

CREATE TABLE IF NOT EXISTS "mining_reward_allocations" (
    "id" BIGSERIAL NOT NULL,
    "mining_date" DATE NOT NULL,
    "contribution_record_id" BIGINT NOT NULL,
    "source_adoption_id" BIGINT NOT NULL,
    "source_account_sequence" VARCHAR(20) NOT NULL,
    "owner_account_sequence" VARCHAR(20) NOT NULL,
    "contribution_type" VARCHAR(30) NOT NULL,
    "contribution_amount" DECIMAL(30, 10) NOT NULL,
    "network_total_contribution" DECIMAL(30, 10) NOT NULL,
    "contribution_ratio" DECIMAL(30, 18) NOT NULL,
    "daily_mining_pool" DECIMAL(30, 10) NOT NULL,
    "reward_amount" DECIMAL(30, 10) NOT NULL,
    "allocation_status" VARCHAR(20) NOT NULL,
    "is_unlocked" BOOLEAN NOT NULL,
    "allocated_to_account_sequence" VARCHAR(20),
    "allocated_to_system_account" VARCHAR(20),
    "unlocked_reason" VARCHAR(200),
    "owner_has_adopted" BOOLEAN NOT NULL,
    "owner_direct_referral_count" INTEGER NOT NULL,
    "owner_unlocked_level_depth" INTEGER NOT NULL,
    "owner_unlocked_bonus_tiers" INTEGER NOT NULL,
    "remark" VARCHAR(500),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "mining_reward_allocations_pkey" PRIMARY KEY ("id")
);

CREATE INDEX IF NOT EXISTS "mining_reward_allocations_mining_date_idx" ON "mining_reward_allocations"("mining_date");
CREATE INDEX IF NOT EXISTS "mining_reward_allocations_owner_account_sequence_mining_date_idx" ON "mining_reward_allocations"("owner_account_sequence", "mining_date");
CREATE INDEX IF NOT EXISTS "mining_reward_allocations_source_account_sequence_idx" ON "mining_reward_allocations"("source_account_sequence");
CREATE INDEX IF NOT EXISTS "mining_reward_allocations_source_adoption_id_idx" ON "mining_reward_allocations"("source_adoption_id");
CREATE INDEX IF NOT EXISTS "mining_reward_allocations_allocation_status_idx" ON "mining_reward_allocations"("allocation_status");
CREATE INDEX IF NOT EXISTS "mining_reward_allocations_contribution_record_id_idx" ON "mining_reward_allocations"("contribution_record_id");

-- ==================== 每日挖矿收益汇总 ====================

CREATE TABLE IF NOT EXISTS "daily_mining_reward_summaries" (
    "id" BIGSERIAL NOT NULL,
    "mining_date" DATE NOT NULL,
    "account_sequence" VARCHAR(20) NOT NULL,
    "unlocked_reward" DECIMAL(30, 10) NOT NULL DEFAULT 0,
    "pending_reward_to_hq" DECIMAL(30, 10) NOT NULL DEFAULT 0,
    "personal_reward" DECIMAL(30, 10) NOT NULL DEFAULT 0,
    "level_reward" DECIMAL(30, 10) NOT NULL DEFAULT 0,
    "bonus_reward" DECIMAL(30, 10) NOT NULL DEFAULT 0,
    "pending_level_to_hq" DECIMAL(30, 10) NOT NULL DEFAULT 0,
    "pending_bonus_to_hq" DECIMAL(30, 10) NOT NULL DEFAULT 0,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "daily_mining_reward_summaries_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX IF NOT EXISTS "daily_mining_reward_summaries_mining_date_account_sequence_key"
    ON "daily_mining_reward_summaries"("mining_date", "account_sequence");
CREATE INDEX IF NOT EXISTS "daily_mining_reward_summaries_mining_date_idx" ON "daily_mining_reward_summaries"("mining_date");
CREATE INDEX IF NOT EXISTS "daily_mining_reward_summaries_account_sequence_idx" ON "daily_mining_reward_summaries"("account_sequence");

-- ==================== 总部待解锁收益明细 ====================

CREATE TABLE IF NOT EXISTS "headquarters_pending_rewards" (
    "id" BIGSERIAL NOT NULL,
    "mining_date" DATE NOT NULL,
    "would_be_account_sequence" VARCHAR(20) NOT NULL,
    "source_adoption_id" BIGINT NOT NULL,
    "source_account_sequence" VARCHAR(20) NOT NULL,
    "contribution_record_id" BIGINT NOT NULL,
    "contribution_type" VARCHAR(30) NOT NULL,
    "contribution_amount" DECIMAL(30, 10) NOT NULL,
    "reward_amount" DECIMAL(30, 10) NOT NULL,
    "reason" VARCHAR(200) NOT NULL,
    "owner_has_adopted" BOOLEAN NOT NULL,
    "owner_direct_referral_count" INTEGER NOT NULL,
    "required_condition" VARCHAR(100) NOT NULL,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "headquarters_pending_rewards_pkey" PRIMARY KEY ("id")
);

CREATE INDEX IF NOT EXISTS "headquarters_pending_rewards_mining_date_idx" ON "headquarters_pending_rewards"("mining_date");
CREATE INDEX IF NOT EXISTS "headquarters_pending_rewards_would_be_account_sequence_idx" ON "headquarters_pending_rewards"("would_be_account_sequence");
CREATE INDEX IF NOT EXISTS "headquarters_pending_rewards_source_adoption_id_idx" ON "headquarters_pending_rewards"("source_adoption_id");

-- ==================== 初始化系统账户 ====================

INSERT INTO "system_mining_accounts" ("id", "account_type", "name", "totalMined", "availableBalance", "totalContribution", "updated_at")
VALUES
    (gen_random_uuid(), 'OPERATION', '运营账户', 0, 0, 0, NOW()),
    (gen_random_uuid(), 'PROVINCE', '省公司账户', 0, 0, 0, NOW()),
    (gen_random_uuid(), 'CITY', '市公司账户', 0, 0, 0, NOW()),
    (gen_random_uuid(), 'HEADQUARTERS', '总部账户', 0, 0, 0, NOW())
ON CONFLICT ("account_type") DO NOTHING;
