import { VideoModel } from './lib/db/video';
import { TagModel } from './lib/db/tag';
import { TagVideoModel } from './lib/db/tag_video';
import pool from './lib/mysql';

async function main() {
  try {
    console.log('Starting CRUD operations test...');

    // Create a video
    const videoData = {
      genre: 'Sci-Fi',
      sub_genre: 'Cyberpunk',
      scene: 'A rainy night in a futuristic city',
      action: 'A detective chasing a rogue android',
      camera: 'Low-angle shot, neon lights reflecting on wet pavement',
      image_prompt: 'cyberpunk city rain neon',
      video_prompt: 'detective chase android rain',
      image_path: '/images/test.png',
      video_path: '/videos/test.mp4',
    };
    const videoId = await VideoModel.create(videoData);
    console.log(`Created video with ID: ${videoId}`);

    // Create a tag
    const tagData = { tag: 'cyberpunk' };
    const tagId = await TagModel.create(tagData);
    console.log(`Created tag with ID: ${tagId}`);

    // Associate tag with video
    const tagVideoId = await TagVideoModel.create({ tag_id: tagId, video_id: videoId });
    console.log(`Associated tag ${tagId} with video ${videoId}. Association ID: ${tagVideoId}`);

    // Retrieve and verify
    const video = await VideoModel.getById(videoId);
    console.log('Retrieved video:', video);
    const tag = await TagModel.getById(tagId);
    console.log('Retrieved tag:', tag);
    const videoTags = await TagVideoModel.getByVideoId(videoId);
    console.log('Retrieved video tags:', videoTags);

    // Update
    await VideoModel.update(videoId, { scene: 'A sunny day in a futuristic city' });
    const updatedVideo = await VideoModel.getById(videoId);
    console.log('Updated video:', updatedVideo);

    await TagModel.update(tagId, { tag: 'dystopian' });
    const updatedTag = await TagModel.getById(tagId);
    console.log('Updated tag:', updatedTag);

    // Cleanup
    console.log('Cleaning up created records...');
    await TagVideoModel.delete(tagVideoId);
    console.log(`Deleted tag_video association with ID: ${tagVideoId}`);
    await VideoModel.delete(videoId);
    console.log(`Deleted video with ID: ${videoId}`);
    await TagModel.delete(tagId);
    console.log(`Deleted tag with ID: ${tagId}`);

    console.log('Test completed successfully.');
  } catch (error) {
    console.error('An error occurred during the test:', error);
  } finally {
    await pool.end();
    process.exit();
  }
}

main();
