-- Create maintenance_logs table
CREATE TABLE IF NOT EXISTS maintenance_logs (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id VARCHAR(255) NOT NULL,
  vehicle_id UUID NOT NULL,
  date DATE NOT NULL,
  odometer INTEGER NOT NULL,
  type VARCHAR(100) NOT NULL, -- oil_change, tire_rotation, etc.
  description TEXT,
  cost DECIMAL(10, 2),
  shop_name VARCHAR(200),
  notes TEXT,
  next_due_date DATE,
  next_due_mileage INTEGER,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  
  CONSTRAINT fk_maintenance_vehicle
    FOREIGN KEY (vehicle_id)
    REFERENCES vehicles(id)
    ON DELETE CASCADE
);

-- Create maintenance_schedules table
CREATE TABLE IF NOT EXISTS maintenance_schedules (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  vehicle_id UUID NOT NULL,
  type VARCHAR(100) NOT NULL,
  interval_months INTEGER,
  interval_miles INTEGER,
  last_performed_date DATE,
  last_performed_mileage INTEGER,
  next_due_date DATE,
  next_due_mileage INTEGER,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  
  CONSTRAINT fk_schedule_vehicle
    FOREIGN KEY (vehicle_id)
    REFERENCES vehicles(id)
    ON DELETE CASCADE,
  
  CONSTRAINT unique_vehicle_maintenance_type
    UNIQUE(vehicle_id, type)
);

-- Create indexes
CREATE INDEX idx_maintenance_logs_user_id ON maintenance_logs(user_id);
CREATE INDEX idx_maintenance_logs_vehicle_id ON maintenance_logs(vehicle_id);
CREATE INDEX idx_maintenance_logs_date ON maintenance_logs(date DESC);
CREATE INDEX idx_maintenance_logs_type ON maintenance_logs(type);

CREATE INDEX idx_maintenance_schedules_vehicle_id ON maintenance_schedules(vehicle_id);
CREATE INDEX idx_maintenance_schedules_next_due_date ON maintenance_schedules(next_due_date);

-- Add triggers
CREATE TRIGGER update_maintenance_logs_updated_at
  BEFORE UPDATE ON maintenance_logs
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_maintenance_schedules_updated_at
  BEFORE UPDATE ON maintenance_schedules
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();