-- Fix Migration: Merge Doctors and Nurses into HR (Employees) - Cleanup

-- 1. Drop dependent tables that reference doctors
DROP TABLE IF EXISTS doctor_schedules;

-- 2. Fix Visits Nurse ID
-- Add temp column if it doesn't exist (it wasn't added in previous migration)
ALTER TABLE visits ADD COLUMN IF NOT EXISTS nurse_employee_id INT NULL;

-- Migrate data from nurses table to visits.nurse_employee_id
UPDATE visits v 
JOIN nurses n ON v.nurse_id = n.id 
SET v.nurse_employee_id = n.employee_id 
WHERE n.employee_id IS NOT NULL;

-- Drop old FK on visits.nurse_id
ALTER TABLE visits DROP FOREIGN KEY IF EXISTS fk_visit_nurse;

-- Drop old column visits.nurse_id
-- We use a check to avoid error if it was already dropped (though unlikely)
ALTER TABLE visits DROP COLUMN nurse_id;

-- Rename new column to nurse_id
ALTER TABLE visits CHANGE COLUMN nurse_employee_id nurse_id INT NULL;

-- Add new FK to employees
ALTER TABLE visits DROP FOREIGN KEY IF EXISTS fk_visit_nurse_employee;
ALTER TABLE visits ADD CONSTRAINT fk_visit_nurse_employee FOREIGN KEY (nurse_id) REFERENCES employees(id) ON DELETE SET NULL;


-- 3. Fix Appointments Nurse ID
-- Ensure nurse_employee_id exists (might have been created in previous migration)
ALTER TABLE appointments ADD COLUMN IF NOT EXISTS nurse_employee_id INT NULL;

-- Migrate data again just in case
UPDATE appointments a 
JOIN nurses n ON a.nurse_id = n.id 
SET a.nurse_employee_id = n.employee_id 
WHERE n.employee_id IS NOT NULL;

-- Drop old FK on appointments.nurse_id
ALTER TABLE appointments DROP FOREIGN KEY IF EXISTS fk_appointment_nurse;

-- Drop old column appointments.nurse_id
ALTER TABLE appointments DROP COLUMN nurse_id;

-- Rename new column to nurse_id
ALTER TABLE appointments CHANGE COLUMN nurse_employee_id nurse_id INT NULL;

-- Add new FK to employees
ALTER TABLE appointments DROP FOREIGN KEY IF EXISTS fk_appt_nurse_employee;
ALTER TABLE appointments ADD CONSTRAINT fk_appt_nurse_employee FOREIGN KEY (nurse_id) REFERENCES employees(id) ON DELETE SET NULL;


-- 4. Drop obsolete tables
-- Now that FKs are gone, this should succeed.
DROP TABLE IF EXISTS doctors;
DROP TABLE IF EXISTS nurses;
