// import redisClient from './redis-client';
import redisClient from 'src/lib/redis-client';
import { db } from '../db/db_index';
import { productTagInfo } from '../db/schema';
import { eq } from 'drizzle-orm';
import { generateSignedUrlFromS3Url } from 'src/lib/s3-client';

// Tag Type (matches getDashboardTags return)
interface Tag {
  id: number;
  tagName: string;
  imageUrl: string | null;
  isDashboardTag: boolean;
}

export async function initializeProductTagStore(): Promise<void> {
  try {
    console.log('Initializing product tag store in Redis...');

    // Fetch all tags
    const tagsData = await db
      .select({
        id: productTagInfo.id,
        tagName: productTagInfo.tagName,
        imageUrl: productTagInfo.imageUrl,
        isDashboardTag: productTagInfo.isDashboardTag,
      })
      .from(productTagInfo);

    // Store each tag in Redis
    for (const tag of tagsData) {
      const signedImageUrl = tag.imageUrl ? await generateSignedUrlFromS3Url(tag.imageUrl) : null;
      
      const tagObj: Tag = {
        id: tag.id,
        tagName: tag.tagName,
        imageUrl: signedImageUrl,
        isDashboardTag: tag.isDashboardTag,
      };

      await redisClient.set(`tag:${tag.id}`, JSON.stringify(tagObj));
    }

    console.log('Product tag store initialized successfully');
  } catch (error) {
    console.error('Error initializing product tag store:', error);
  }
}

export async function getTagById(id: number): Promise<Tag | null> {
  try {
    const key = `tag:${id}`;
    const data = await redisClient.get(key);
    if (!data) return null;
    return JSON.parse(data) as Tag;
  } catch (error) {
    console.error(`Error getting tag ${id}:`, error);
    return null;
  }
}

export async function getAllTags(): Promise<Tag[]> {
  try {
    // Get all keys matching the pattern "tag:*"
    const keys = await redisClient.KEYS('tag:*');

    if (keys.length === 0) {
      return [];
    }

    // Get all tags using MGET for better performance
    const tagsData = await redisClient.MGET(keys);

    const tags: Tag[] = [];
    for (const tagData of tagsData) {
      if (tagData) {
        tags.push(JSON.parse(tagData) as Tag);
      }
    }

    return tags;
  } catch (error) {
    console.error('Error getting all tags:', error);
    return [];
  }
}

export async function getDashboardTags(): Promise<Tag[]> {
  try {
    // Get all keys matching the pattern "tag:*"
    const keys = await redisClient.KEYS('tag:*');

    if (keys.length === 0) {
      return [];
    }

    // Get all tags using MGET for better performance
    const tagsData = await redisClient.MGET(keys);

    const dashboardTags: Tag[] = [];
    for (const tagData of tagsData) {
      if (tagData) {
        const tag = JSON.parse(tagData) as Tag;
        if (tag.isDashboardTag) {
          dashboardTags.push(tag);
        }
      }
    }

    return dashboardTags;
  } catch (error) {
    console.error('Error getting dashboard tags:', error);
    return [];
  }
}