-- ====================================================================================================
-- Event ID 타입 변경 DDL (UUID → VARCHAR(50)) - PostgreSQL
-- ====================================================================================================
-- 작성일: 2025-10-29
-- 작성자: Backend Development Team
-- 설명: Event 엔티티의 eventId가 String 타입으로 변경됨에 따라 관련 테이블들의 event_id 컬럼 타입을 UUID에서 VARCHAR(50)으로 변경합니다.
-- 영향 범위:
--   - events 테이블 (Primary Key)
--   - event_channels 테이블 (Foreign Key)
--   - generated_images 테이블 (Foreign Key)
--   - ai_recommendations 테이블 (Foreign Key)
--   - jobs 테이블 (Foreign Key)
-- ====================================================================================================

-- 0. 현재 상태 확인 (실행 전 확인용)
-- ====================================================================================================
-- 각 테이블의 event_id 컬럼 타입 확인
-- SELECT table_name, column_name, data_type
-- FROM information_schema.columns
-- WHERE column_name = 'event_id'
-- AND table_schema = 'public'
-- ORDER BY table_name;

-- event_id 관련 모든 외래키 제약조건 확인
-- SELECT
--     tc.constraint_name,
--     tc.table_name,
--     kcu.column_name,
--     ccu.table_name AS foreign_table_name,
--     ccu.column_name AS foreign_column_name
-- FROM information_schema.table_constraints AS tc
-- JOIN information_schema.key_column_usage AS kcu
--     ON tc.constraint_name = kcu.constraint_name
--     AND tc.table_schema = kcu.table_schema
-- JOIN information_schema.constraint_column_usage AS ccu
--     ON ccu.constraint_name = tc.constraint_name
--     AND ccu.table_schema = tc.table_schema
-- WHERE tc.constraint_type = 'FOREIGN KEY'
-- AND kcu.column_name = 'event_id'
-- AND tc.table_schema = 'public';

-- 1. 외래키 제약조건 전체 제거
-- ====================================================================================================
-- JPA가 자동 생성한 제약조건 이름도 포함하여 모두 제거

-- event_channels 테이블의 모든 event_id 관련 외래키 제거
DO $$
DECLARE
    constraint_name TEXT;
BEGIN
    FOR constraint_name IN
        SELECT tc.constraint_name
        FROM information_schema.table_constraints AS tc
        JOIN information_schema.key_column_usage AS kcu
            ON tc.constraint_name = kcu.constraint_name
        WHERE tc.constraint_type = 'FOREIGN KEY'
        AND tc.table_name = 'event_channels'
        AND kcu.column_name = 'event_id'
        AND tc.table_schema = 'public'
    LOOP
        EXECUTE 'ALTER TABLE event_channels DROP CONSTRAINT IF EXISTS ' || constraint_name;
    END LOOP;
END $$;

-- generated_images 테이블의 모든 event_id 관련 외래키 제거
DO $$
DECLARE
    constraint_name TEXT;
BEGIN
    FOR constraint_name IN
        SELECT tc.constraint_name
        FROM information_schema.table_constraints AS tc
        JOIN information_schema.key_column_usage AS kcu
            ON tc.constraint_name = kcu.constraint_name
        WHERE tc.constraint_type = 'FOREIGN KEY'
        AND tc.table_name = 'generated_images'
        AND kcu.column_name = 'event_id'
        AND tc.table_schema = 'public'
    LOOP
        EXECUTE 'ALTER TABLE generated_images DROP CONSTRAINT IF EXISTS ' || constraint_name;
    END LOOP;
END $$;

-- ai_recommendations 테이블의 모든 event_id 관련 외래키 제거
DO $$
DECLARE
    constraint_name TEXT;
BEGIN
    FOR constraint_name IN
        SELECT tc.constraint_name
        FROM information_schema.table_constraints AS tc
        JOIN information_schema.key_column_usage AS kcu
            ON tc.constraint_name = kcu.constraint_name
        WHERE tc.constraint_type = 'FOREIGN KEY'
        AND tc.table_name = 'ai_recommendations'
        AND kcu.column_name = 'event_id'
        AND tc.table_schema = 'public'
    LOOP
        EXECUTE 'ALTER TABLE ai_recommendations DROP CONSTRAINT IF EXISTS ' || constraint_name;
    END LOOP;
END $$;

-- jobs 테이블의 모든 event_id 관련 외래키 제거
DO $$
DECLARE
    constraint_name TEXT;
BEGIN
    FOR constraint_name IN
        SELECT tc.constraint_name
        FROM information_schema.table_constraints AS tc
        JOIN information_schema.key_column_usage AS kcu
            ON tc.constraint_name = kcu.constraint_name
        WHERE tc.constraint_type = 'FOREIGN KEY'
        AND tc.table_name = 'jobs'
        AND kcu.column_name = 'event_id'
        AND tc.table_schema = 'public'
    LOOP
        EXECUTE 'ALTER TABLE jobs DROP CONSTRAINT IF EXISTS ' || constraint_name;
    END LOOP;
END $$;


-- 2. 컬럼 타입 변경 (UUID/기타 → VARCHAR)
-- ====================================================================================================
-- 현재 타입에 관계없이 VARCHAR(50)으로 변환
-- UUID, BIGINT 등 모든 타입을 텍스트로 변환

-- events 테이블의 event_id 컬럼 타입 변경 (Primary Key)
DO $$
BEGIN
    ALTER TABLE events ALTER COLUMN event_id TYPE VARCHAR(50) USING event_id::text;
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'events.event_id 변환 중 오류: %', SQLERRM;
END $$;

-- event_channels 테이블의 event_id 컬럼 타입 변경
DO $$
BEGIN
    ALTER TABLE event_channels ALTER COLUMN event_id TYPE VARCHAR(50) USING event_id::text;
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'event_channels.event_id 변환 중 오류: %', SQLERRM;
END $$;

-- generated_images 테이블의 event_id 컬럼 타입 변경
DO $$
BEGIN
    ALTER TABLE generated_images ALTER COLUMN event_id TYPE VARCHAR(50) USING event_id::text;
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'generated_images.event_id 변환 중 오류: %', SQLERRM;
END $$;

-- ai_recommendations 테이블의 event_id 컬럼 타입 변경
DO $$
BEGIN
    ALTER TABLE ai_recommendations ALTER COLUMN event_id TYPE VARCHAR(50) USING event_id::text;
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'ai_recommendations.event_id 변환 중 오류: %', SQLERRM;
END $$;

-- jobs 테이블의 event_id 컬럼 타입 변경 (NULL 허용)
DO $$
BEGIN
    ALTER TABLE jobs ALTER COLUMN event_id TYPE VARCHAR(50) USING event_id::text;
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'jobs.event_id 변환 중 오류: %', SQLERRM;
END $$;


-- 3. 외래키 제약조건 재생성
-- ====================================================================================================

-- event_channels 테이블의 외래키 재생성
ALTER TABLE event_channels
ADD CONSTRAINT fk_event_channels_event
FOREIGN KEY (event_id) REFERENCES events(event_id)
ON DELETE CASCADE;

-- generated_images 테이블의 외래키 재생성
ALTER TABLE generated_images
ADD CONSTRAINT fk_generated_images_event
FOREIGN KEY (event_id) REFERENCES events(event_id)
ON DELETE CASCADE;

-- ai_recommendations 테이블의 외래키 재생성
ALTER TABLE ai_recommendations
ADD CONSTRAINT fk_ai_recommendations_event
FOREIGN KEY (event_id) REFERENCES events(event_id)
ON DELETE CASCADE;

-- jobs 테이블의 외래키 재생성
ALTER TABLE jobs
ADD CONSTRAINT fk_jobs_event
FOREIGN KEY (event_id) REFERENCES events(event_id)
ON DELETE SET NULL;


-- 4. 인덱스 확인 (옵션)
-- ====================================================================================================
-- 기존 인덱스들이 자동으로 유지되는지 확인
-- \d events
-- \d event_channels
-- \d generated_images
-- \d ai_recommendations
-- \d jobs


-- ====================================================================================================
-- 롤백 스크립트 (필요시 사용)
-- ====================================================================================================
/*
-- 1. 외래키 제약조건 제거
ALTER TABLE event_channels DROP CONSTRAINT IF EXISTS fk_event_channels_event;
ALTER TABLE generated_images DROP CONSTRAINT IF EXISTS fk_generated_images_event;
ALTER TABLE ai_recommendations DROP CONSTRAINT IF EXISTS fk_ai_recommendations_event;
ALTER TABLE jobs DROP CONSTRAINT IF EXISTS fk_jobs_event;

-- 2. 컬럼 타입 원복 (VARCHAR → UUID)
ALTER TABLE events ALTER COLUMN event_id TYPE UUID USING event_id::UUID;
ALTER TABLE event_channels ALTER COLUMN event_id TYPE UUID USING event_id::UUID;
ALTER TABLE generated_images ALTER COLUMN event_id TYPE UUID USING event_id::UUID;
ALTER TABLE ai_recommendations ALTER COLUMN event_id TYPE UUID USING event_id::UUID;
ALTER TABLE jobs ALTER COLUMN event_id TYPE UUID USING event_id::UUID;

-- 4. 외래키 제약조건 재생성
ALTER TABLE event_channels ADD CONSTRAINT fk_event_channels_event FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE CASCADE;
ALTER TABLE generated_images ADD CONSTRAINT fk_generated_images_event FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE CASCADE;
ALTER TABLE ai_recommendations ADD CONSTRAINT fk_ai_recommendations_event FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE CASCADE;
ALTER TABLE jobs ADD CONSTRAINT fk_jobs_event FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE SET NULL;
*/
