import { db } from '../config/database.js';
import { sql } from 'drizzle-orm';

async function createProjectUsersTable() {
  console.log('⏳ Creating project_users table...');

  try {
    // Check if table exists
    const result = await db.execute(sql`
      SELECT EXISTS (
        SELECT FROM information_schema.tables
        WHERE table_schema = 'public'
        AND table_name = 'project_users'
      );
    `);

    const tableExists = result.rows[0]?.exists;

    if (tableExists) {
      console.log('✅ project_users table already exists');
      process.exit(0);
    }

    // Create the table
    await db.execute(sql`
      CREATE TABLE IF NOT EXISTS project_users (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
          user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
          role TEXT,
          added_by UUID REFERENCES users(id) ON DELETE SET NULL,
          added_at TIMESTAMP NOT NULL DEFAULT NOW(),
          CONSTRAINT project_user_unique UNIQUE(project_id, user_id)
      );
    `);

    // Create indexes
    await db.execute(sql`
      CREATE INDEX IF NOT EXISTS idx_project_users_project_id ON project_users(project_id);
    `);

    await db.execute(sql`
      CREATE INDEX IF NOT EXISTS idx_project_users_user_id ON project_users(user_id);
    `);

    console.log('✅ project_users table created successfully');
    process.exit(0);
  } catch (error) {
    console.error('❌ Failed to create table:', error);
    process.exit(1);
  }
}

createProjectUsersTable();
