CREATE TABLE patients (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  clinic_id UUID NOT NULL REFERENCES clinics(id) ON DELETE CASCADE,
  first_name TEXT NOT NULL,
  last_name TEXT NOT NULL,
  date_of_birth DATE,
  gender TEXT CHECK (gender IN ('M', 'F', 'otro')),
  curp TEXT,
  phone TEXT,
  email TEXT,
  address JSONB,
  blood_type TEXT,
  allergies TEXT[] DEFAULT '{}',
  emergency_contact JSONB,
  notes TEXT,
  source TEXT,
  is_active BOOLEAN NOT NULL DEFAULT TRUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_patients_clinic ON patients(clinic_id);
CREATE INDEX idx_patients_name ON patients(clinic_id, last_name, first_name);
CREATE INDEX idx_patients_phone ON patients(clinic_id, phone);

ALTER TABLE patients ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can view clinic patients" ON patients FOR SELECT USING (clinic_id = auth.clinic_id());
CREATE POLICY "Users can insert clinic patients" ON patients FOR INSERT WITH CHECK (clinic_id = auth.clinic_id());
CREATE POLICY "Users can update clinic patients" ON patients FOR UPDATE USING (clinic_id = auth.clinic_id());
