-- Migration: Create ownership_costs table
-- Issue: #15
-- Description: Store vehicle ownership costs (insurance, registration, tax, other)
-- with explicit date ranges and optional document association

CREATE TABLE IF NOT EXISTS ownership_costs (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id VARCHAR(255) NOT NULL,
  vehicle_id UUID NOT NULL,
  document_id UUID,
  cost_type VARCHAR(50) NOT NULL,
  description TEXT,
  amount DECIMAL(12, 2) NOT NULL,
  interval VARCHAR(20) NOT NULL,
  start_date DATE NOT NULL,
  end_date DATE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,

  -- Foreign key to vehicles (cascade delete)
  CONSTRAINT fk_ownership_costs_vehicle
    FOREIGN KEY (vehicle_id)
    REFERENCES vehicles(id)
    ON DELETE CASCADE,

  -- Foreign key to documents (set null on delete)
  CONSTRAINT fk_ownership_costs_document
    FOREIGN KEY (document_id)
    REFERENCES documents(id)
    ON DELETE SET NULL,

  -- Enforce valid cost types
  CONSTRAINT chk_ownership_costs_type
    CHECK (cost_type IN ('insurance', 'registration', 'tax', 'other')),

  -- Enforce valid intervals
  CONSTRAINT chk_ownership_costs_interval
    CHECK (interval IN ('monthly', 'semi_annual', 'annual', 'one_time')),

  -- Enforce non-negative amounts
  CONSTRAINT chk_ownership_costs_amount_non_negative
    CHECK (amount >= 0),

  -- Enforce end_date >= start_date when end_date is provided
  CONSTRAINT chk_ownership_costs_date_range
    CHECK (end_date IS NULL OR end_date >= start_date)
);

-- Create indexes for common queries
CREATE INDEX IF NOT EXISTS idx_ownership_costs_user_id ON ownership_costs(user_id);
CREATE INDEX IF NOT EXISTS idx_ownership_costs_vehicle_id ON ownership_costs(vehicle_id);
CREATE INDEX IF NOT EXISTS idx_ownership_costs_cost_type ON ownership_costs(cost_type);
CREATE INDEX IF NOT EXISTS idx_ownership_costs_start_date ON ownership_costs(start_date DESC);
CREATE INDEX IF NOT EXISTS idx_ownership_costs_document_id ON ownership_costs(document_id) WHERE document_id IS NOT NULL;

-- Add updated_at trigger
DROP TRIGGER IF EXISTS update_ownership_costs_updated_at ON ownership_costs;
CREATE TRIGGER update_ownership_costs_updated_at
  BEFORE UPDATE ON ownership_costs
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();
