-- Documents feature schema
-- Depends on vehicles table and update_updated_at_column() from vehicles feature

CREATE TABLE IF NOT EXISTS documents (
  id UUID PRIMARY KEY,
  user_id VARCHAR(255) NOT NULL,
  vehicle_id UUID NOT NULL REFERENCES vehicles(id) ON DELETE CASCADE,
  document_type VARCHAR(32) NOT NULL CHECK (document_type IN ('insurance','registration')),
  title VARCHAR(200) NOT NULL,
  notes TEXT NULL,
  details JSONB NULL,

  storage_bucket VARCHAR(128) NULL,
  storage_key VARCHAR(512) NULL,
  file_name VARCHAR(255) NULL,
  content_type VARCHAR(128) NULL,
  file_size BIGINT NULL,
  file_hash VARCHAR(128) NULL,

  issued_date DATE NULL,
  expiration_date DATE NULL,

  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL,
  deleted_at TIMESTAMP WITHOUT TIME ZONE NULL
);

-- Update trigger for updated_at
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_trigger WHERE tgname = 'set_timestamp_documents'
  ) THEN
    CREATE TRIGGER set_timestamp_documents
    BEFORE UPDATE ON documents
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();
  END IF;
END $$;

-- Indexes
CREATE INDEX IF NOT EXISTS idx_documents_user_id ON documents(user_id);
CREATE INDEX IF NOT EXISTS idx_documents_vehicle_id ON documents(vehicle_id);
CREATE INDEX IF NOT EXISTS idx_documents_user_vehicle ON documents(user_id, vehicle_id);
CREATE INDEX IF NOT EXISTS idx_documents_type ON documents(document_type);
CREATE INDEX IF NOT EXISTS idx_documents_expiration ON documents(expiration_date);

