-- 1. Create Lookup Tables (Idempotent)
CREATE TABLE IF NOT EXISTS public.departments (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL
);

CREATE TABLE IF NOT EXISTS public.sections (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    department_id UUID REFERENCES public.departments(id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL,
    UNIQUE(department_id, name)
);

CREATE TABLE IF NOT EXISTS public.employment_types (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL
);

CREATE TABLE IF NOT EXISTS public.job_titles (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL
);

-- 2. Update Employees Table (Idempotent)
DO $$
BEGIN
    -- Add columns if they don't exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='first_name') THEN
        ALTER TABLE public.employees ADD COLUMN first_name TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='last_name') THEN
        ALTER TABLE public.employees ADD COLUMN last_name TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='email') THEN
        ALTER TABLE public.employees ADD COLUMN email TEXT UNIQUE;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='photo_url') THEN
        ALTER TABLE public.employees ADD COLUMN photo_url TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='department_id') THEN
        ALTER TABLE public.employees ADD COLUMN department_id UUID REFERENCES public.departments(id);
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='section_id') THEN
        ALTER TABLE public.employees ADD COLUMN section_id UUID REFERENCES public.sections(id);
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='employment_type_id') THEN
        ALTER TABLE public.employees ADD COLUMN employment_type_id UUID REFERENCES public.employment_types(id);
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='job_title_id') THEN
        ALTER TABLE public.employees ADD COLUMN job_title_id UUID REFERENCES public.job_titles(id);
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='tc_no') THEN
        ALTER TABLE public.employees ADD COLUMN tc_no TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='birth_date') THEN
        ALTER TABLE public.employees ADD COLUMN birth_date DATE;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='birth_place') THEN
        ALTER TABLE public.employees ADD COLUMN birth_place TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='gender') THEN
        ALTER TABLE public.employees ADD COLUMN gender TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='address') THEN
        ALTER TABLE public.employees ADD COLUMN address TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='phone1') THEN
        ALTER TABLE public.employees ADD COLUMN phone1 TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='phone2') THEN
        ALTER TABLE public.employees ADD COLUMN phone2 TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='has_driving_license') THEN
        ALTER TABLE public.employees ADD COLUMN has_driving_license BOOLEAN DEFAULT false;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='military_status') THEN
        ALTER TABLE public.employees ADD COLUMN military_status TEXT;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='start_date') THEN
        ALTER TABLE public.employees ADD COLUMN start_date DATE;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='employees' AND column_name='leave_date') THEN
        ALTER TABLE public.employees ADD COLUMN leave_date DATE;
    END IF;
END $$;

-- 2.5 Update Users Table (Idempotent)
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='status') THEN
        ALTER TABLE public.users ADD COLUMN status TEXT DEFAULT 'active';
    END IF;
END $$;

-- 3. Enable RLS for new tables
ALTER TABLE public.departments ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.sections ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.employment_types ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.job_titles ENABLE ROW LEVEL SECURITY;

-- Idempotent Policies
DO $$
BEGIN
    DROP POLICY IF EXISTS "Allow authenticated full access to lookup tables" ON public.departments;
    CREATE POLICY "Allow authenticated full access to lookup tables" ON public.departments FOR ALL TO authenticated USING (true) WITH CHECK (true);
    
    DROP POLICY IF EXISTS "Allow authenticated full access to sections" ON public.sections;
    CREATE POLICY "Allow authenticated full access to sections" ON public.sections FOR ALL TO authenticated USING (true) WITH CHECK (true);
    
    DROP POLICY IF EXISTS "Allow authenticated full access to employment_types" ON public.employment_types;
    CREATE POLICY "Allow authenticated full access to employment_types" ON public.employment_types FOR ALL TO authenticated USING (true) WITH CHECK (true);
    
    DROP POLICY IF EXISTS "Allow authenticated full access to job_titles" ON public.job_titles;
    CREATE POLICY "Allow authenticated full access to job_titles" ON public.job_titles FOR ALL TO authenticated USING (true) WITH CHECK (true);
END $$;

-- 4. Storage Bucket for Photos (Idempotent)
DO $$
BEGIN
    INSERT INTO storage.buckets (id, name, public) 
    VALUES ('employee-photos', 'employee-photos', true)
    ON CONFLICT (id) DO NOTHING;
END $$;

DO $$
BEGIN
    DROP POLICY IF EXISTS "Public Access to Employee Photos" ON storage.objects;
    CREATE POLICY "Public Access to Employee Photos" ON storage.objects FOR SELECT TO public USING (bucket_id = 'employee-photos');
    
    DROP POLICY IF EXISTS "Authenticated users can upload employee photos" ON storage.objects;
    CREATE POLICY "Authenticated users can upload employee photos" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'employee-photos');
END $$;

-- 5. Trigger for auto-deactivation
CREATE OR REPLACE FUNCTION public.handle_employee_leave()
RETURNS TRIGGER AS $$
BEGIN
    IF NEW.leave_date IS NOT NULL AND (OLD.leave_date IS NULL OR OLD.leave_date != NEW.leave_date) THEN
        -- Mark employee as inactive
        NEW.status := 'inactive';
        
        -- Mark linked user as inactive if exists
        IF NEW.user_id IS NOT NULL THEN
            UPDATE public.users SET status = 'inactive' WHERE id = NEW.user_id;
        END IF;
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS on_employee_leave ON public.employees;
CREATE TRIGGER on_employee_leave
BEFORE UPDATE ON public.employees
FOR EACH ROW
EXECUTE FUNCTION public.handle_employee_leave();

-- 6. Seed some initial data (Idempotent)
INSERT INTO public.departments (name) VALUES ('Yönetim'), ('Bilgi İşlem'), ('İnsan Kaynakları'), ('Satış'), ('Üretim') ON CONFLICT (name) DO NOTHING;
INSERT INTO public.employment_types (name) VALUES ('Tam Zamanlı'), ('Yarı Zamanlı'), ('Stajyer'), ('Sözleşmeli') ON CONFLICT (name) DO NOTHING;
INSERT INTO public.job_titles (name) VALUES ('Müdür'), ('Yazılım Geliştirici'), ('IK Uzmanı'), ('Satış Temsilcisi'), ('Operatör') ON CONFLICT (name) DO NOTHING;
