-- Enable UUID extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Create Users table in public schema
CREATE TABLE IF NOT EXISTS public.users (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    email TEXT UNIQUE NOT NULL,
    encrypted_password TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

-- Attempt to migrate data from Supabase auth.users if it exists
DO $$
BEGIN
    IF EXISTS (SELECT FROM pg_tables WHERE schemaname = 'auth' AND tablename = 'users') THEN
        INSERT INTO public.users (id, email, encrypted_password, created_at, updated_at)
        SELECT 
            id, 
            email, 
            encrypted_password, 
            created_at, 
            COALESCE(updated_at, created_at)
        FROM auth.users
        WHERE email NOT IN (SELECT email FROM public.users)
        ON CONFLICT (id) DO NOTHING;
    END IF;
END $$;

-- Update profiles foreign key ONLY if profiles table exists
DO $$
BEGIN
    IF EXISTS (SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename = 'profiles') THEN
        ALTER TABLE public.profiles DROP CONSTRAINT IF EXISTS profiles_id_fkey;

        ALTER TABLE public.profiles 
            ADD CONSTRAINT profiles_id_fkey 
            FOREIGN KEY (id) 
            REFERENCES public.users(id) 
            ON DELETE CASCADE;
    END IF;
END $$;
