import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, EntityManager } from 'typeorm';
import { SeekerSocialLinks } from './entities/seeker_social_links.entity';

@Injectable()
export class SeekerSocialLinksService {
  constructor(
    @InjectRepository(SeekerSocialLinks)
    private readonly seekerSocialLinksRepository: Repository<SeekerSocialLinks>,
    private readonly entityManager: EntityManager,
  ) {}

  private async getSeekerProfileId(userId: number): Promise<number> {
    const profile = await this.entityManager.query(
      'SELECT id FROM seeker_profiles WHERE user_id = ? LIMIT 1',
      [userId]
    );
    if (!profile || profile.length === 0) {
      throw new NotFoundException(`Seeker profile for user ${userId} not found`);
    }
    return profile[0].id;
  }

  // Fetch all records from seeker_social_links table
  async findAll() {
    return this.seekerSocialLinksRepository
      .createQueryBuilder('ssl')
      .orderBy('ssl.id', 'ASC')
      .getMany();
  }

  async updateSocialLinks(userId: number, links: any[]) {
    const seekerProfileId = await this.getSeekerProfileId(userId);

    // Run in transaction to ensure consistency
    return await this.entityManager.transaction(async (manager) => {
      // Delete all existing links for this profile
      await manager.delete(SeekerSocialLinks, { seeker_id: seekerProfileId });

      // Insert new links
      if (links && links.length > 0) {
        const linksToInsert = links.map(link => ({
          seeker_id: seekerProfileId,
          platform_id: link.platform_id,
          url: link.url,
          created_at: new Date(),
          updated_at: new Date(),
        }));
        await manager.insert(SeekerSocialLinks, linksToInsert);
      }
      return { success: true, message: 'Social links updated successfully' };
    });
  }
}
