-- 统一媒体存储为 COS，并清理 WEB 历史业务数据；管理员配置和用户登录身份保留。
BEGIN;

-- 先解除即将删除媒体对象上的业务引用，避免外键阻止清理。
UPDATE creative_projects
SET cover_asset_id = NULL, source_video_asset_id = NULL, subtitle_asset_id = NULL;
UPDATE project_episodes
SET cover_asset_id = NULL, source_video_asset_id = NULL, subtitle_asset_id = NULL;
UPDATE episode_storyboards
SET active_output_id = NULL, thumbnail_asset_id = NULL;
UPDATE project_assets
SET image_asset_id = NULL, audio_asset_id = NULL;

-- 删除 WEB 任务、项目、媒体和用户个性化数据；不触碰管理员配置表。
DELETE FROM user_prompt_preferences;
DELETE FROM user_model_configs;
DELETE FROM channel_asset_cache;
DELETE FROM generation_outputs;
DELETE FROM generation_tasks;
DO $$
BEGIN
    IF to_regclass('public.canvas_projects') IS NOT NULL THEN
        EXECUTE 'DELETE FROM public.canvas_projects';
    END IF;
    IF to_regclass('public.recharge_orders') IS NOT NULL THEN
        EXECUTE 'DELETE FROM public.recharge_orders';
    END IF;
END $$;
DELETE FROM script_analysis_characters;
DELETE FROM script_analyses;
DELETE FROM point_ledger_allocations;
DELETE FROM point_grants;
DELETE FROM point_ledger;
DELETE FROM episode_continuity_contexts;
DELETE FROM episode_sources;
DELETE FROM drama_parse_tasks;
DELETE FROM drama_parse_batches;
DELETE FROM episode_storyboards;
DELETE FROM project_model_configs;
DELETE FROM project_assets;
DELETE FROM project_episodes;
DELETE FROM drama_import_sessions;
DELETE FROM creative_projects;
DELETE FROM web_refresh_tokens;
DELETE FROM media_assets;

-- 系统提示词属于 ADMIN 配置，用户自定义提示词属于 WEB 数据。
DELETE FROM prompts WHERE scope = 'user';

-- 只保留用户登录所需身份和密码，其余 WEB 状态恢复为新用户状态。
UPDATE web_users
SET point_balance = 0,
    daily_limit = 9999,
    enabled = TRUE,
    avatar_url = NULL,
    avatar_key = NULL,
    session_version = session_version + 1,
    last_online_at = NULL,
    deleted_at = NULL,
    updated_at = CURRENT_TIMESTAMP;

-- 媒体资产的新存储提供方只允许 COS。
ALTER TABLE media_assets DROP CONSTRAINT media_assets_storage_provider_check;
ALTER TABLE media_assets ALTER COLUMN storage_provider SET DEFAULT 'cos';
ALTER TABLE media_assets
    ADD CONSTRAINT media_assets_storage_provider_check CHECK (storage_provider = 'cos');

COMMIT;
