import { pool } from "./db";

export async function createRecentlyViewedTable(): Promise<void> {
  const client = await pool.connect();
  try {
    await client.query(`
      CREATE TABLE IF NOT EXISTS recently_viewed (
        id SERIAL PRIMARY KEY,
        client_id INTEGER NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
        user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        viewed_at TIMESTAMP DEFAULT NOW() NOT NULL
      );
      
      CREATE INDEX IF NOT EXISTS idx_recently_viewed_viewed_at ON recently_viewed(viewed_at DESC);
      CREATE INDEX IF NOT EXISTS idx_recently_viewed_client_user ON recently_viewed(client_id, user_id);
    `);
    console.log("Recently viewed table created successfully");
  } catch (error) {
    console.error("Error creating recently viewed table:", error);
  } finally {
    client.release();
  }
}

// Run the function if this file is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
  createRecentlyViewedTable()
    .then(() => {
      console.log("Recently viewed table setup complete");
      process.exit(0);
    })
    .catch((error) => {
      console.error("Failed to setup recently viewed table:", error);
      process.exit(1);
    });
}