CREATE TABLE doctor_schedules (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  clinic_id UUID NOT NULL REFERENCES clinics(id) ON DELETE CASCADE,
  doctor_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  day_of_week INT NOT NULL CHECK (day_of_week BETWEEN 0 AND 6),
  start_time TIME NOT NULL,
  end_time TIME NOT NULL,
  slot_duration INT NOT NULL DEFAULT 30,
  is_active BOOLEAN NOT NULL DEFAULT TRUE,
  UNIQUE(doctor_id, day_of_week)
);

CREATE TABLE appointments (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  clinic_id UUID NOT NULL REFERENCES clinics(id) ON DELETE CASCADE,
  patient_id UUID NOT NULL REFERENCES patients(id) ON DELETE CASCADE,
  doctor_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  starts_at TIMESTAMPTZ NOT NULL,
  ends_at TIMESTAMPTZ NOT NULL,
  status TEXT NOT NULL DEFAULT 'scheduled' CHECK (status IN ('scheduled','confirmed','in_progress','completed','cancelled','no_show')),
  type TEXT NOT NULL DEFAULT 'seguimiento' CHECK (type IN ('primera_vez','seguimiento','urgencia')),
  reason TEXT,
  notes TEXT,
  reminder_sent BOOLEAN NOT NULL DEFAULT FALSE,
  created_by UUID REFERENCES users(id),
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_appointments_doctor_date ON appointments(doctor_id, starts_at);
CREATE INDEX idx_appointments_patient ON appointments(patient_id);
CREATE INDEX idx_appointments_status ON appointments(clinic_id, status);

ALTER TABLE doctor_schedules ENABLE ROW LEVEL SECURITY;
CREATE POLICY "View clinic schedules" ON doctor_schedules FOR SELECT USING (clinic_id = auth.clinic_id());
CREATE POLICY "Manage clinic schedules" ON doctor_schedules FOR ALL USING (clinic_id = auth.clinic_id());

ALTER TABLE appointments ENABLE ROW LEVEL SECURITY;
CREATE POLICY "View clinic appointments" ON appointments FOR SELECT USING (clinic_id = auth.clinic_id());
CREATE POLICY "Insert clinic appointments" ON appointments FOR INSERT WITH CHECK (clinic_id = auth.clinic_id());
CREATE POLICY "Update clinic appointments" ON appointments FOR UPDATE USING (clinic_id = auth.clinic_id());
