import { Migration } from '../migrate.js'

export const up: Migration['up'] = async (db) => {
  // Resource sharing table for cross-tenant resource sharing
  await db.query(`
    CREATE TABLE IF NOT EXISTS resource_shares (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      resource_id UUID NOT NULL REFERENCES resource_inventory(id) ON DELETE CASCADE,
      source_tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      target_tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      permissions JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      UNIQUE(resource_id, target_tenant_id)
    )
  `)

  // Indexes for resource sharing
  await db.query(`CREATE INDEX IF NOT EXISTS idx_resource_shares_resource_id ON resource_shares(resource_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_resource_shares_source_tenant_id ON resource_shares(source_tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_resource_shares_target_tenant_id ON resource_shares(target_tenant_id)`)

  // Trigger for updated_at
  await db.query(`
    CREATE TRIGGER update_resource_shares_updated_at BEFORE UPDATE ON resource_shares
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)
}

export const down: Migration['down'] = async (db) => {
  await db.query(`DROP TRIGGER IF EXISTS update_resource_shares_updated_at ON resource_shares`)
  await db.query(`DROP INDEX IF EXISTS idx_resource_shares_target_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_resource_shares_source_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_resource_shares_resource_id`)
  await db.query(`DROP TABLE IF EXISTS resource_shares`)
}

