/**
 * Review Widget Service
 * Manage widget branding settings and public widget data
 *
 * All database access uses direct Convex calls via convexQuery/convexMutation.
 */

import { logger } from '@/lib/logger';
import { convexQuery, convexMutation } from '@/lib/convex-client';
import type { WidgetSettingsInput } from '@/lib/validators/reviews.validator';
import type { Id } from '@/convex/_generated/dataModel';

const log = logger.scope('ReviewWidgetService');

// Default settings returned when no custom settings exist
const DEFAULT_WIDGET_SETTINGS = {
  businessName: null,
  businessNameAr: null,
  logoUrl: null,
  primaryColor: '#10b981',
  backgroundColor: '#ffffff',
  textColor: '#1e293b',
  thankYouMessage: null,
  thankYouMessageAr: null,
  showPoweredBy: true,
  customCss: null,
} as const;

// ── Type helpers for Convex docs ──────────────────────────────────────

interface ConvexWidgetSettings {
  _id: string;
  userId: string;
  businessName?: string;
  businessNameAr?: string;
  logoUrl?: string;
  primaryColor: string;
  backgroundColor: string;
  textColor: string;
  thankYouMessage?: string;
  thankYouMessageAr?: string;
  showPoweredBy: boolean;
  customCss?: string;
  createdAt: number;
  updatedAt: number;
}

interface ConvexReview {
  _id: string;
  userId: string;
  customerName: string;
  rating: number;
  title?: string;
  content?: string;
  language: string;
  platform: string;
  isFeatured: boolean;
  featuredOrder?: number;
  createdAt: number;
  updatedAt: number;
}

interface ConvexReviewRequest {
  _id: string;
  userId: string;
  customerName: string;
  language: string;
  questions?: unknown;
  status: string;
  expiresAt: number;
}

// ═══════════════════════════════════════════════════════════════════════
// Widget Settings
// ═══════════════════════════════════════════════════════════════════════

export async function getWidgetSettings(userId: string) {
  const settings = await convexQuery<ConvexWidgetSettings | null>(
    'reviews/queries:getWidgetSettings',
    { userId },
  );

  if (!settings) {
    log.info('No widget settings found, returning defaults', { userId });
    return { userId, ...DEFAULT_WIDGET_SETTINGS };
  }

  return {
    id: settings._id,
    userId: settings.userId,
    businessName: settings.businessName ?? null,
    businessNameAr: settings.businessNameAr ?? null,
    logoUrl: settings.logoUrl ?? null,
    primaryColor: settings.primaryColor,
    backgroundColor: settings.backgroundColor,
    textColor: settings.textColor,
    thankYouMessage: settings.thankYouMessage ?? null,
    thankYouMessageAr: settings.thankYouMessageAr ?? null,
    showPoweredBy: settings.showPoweredBy,
    customCss: settings.customCss ?? null,
    createdAt: new Date(settings.createdAt),
    updatedAt: new Date(settings.updatedAt),
  };
}

export async function upsertWidgetSettings(userId: string, input: WidgetSettingsInput) {
  const convexId = await convexMutation<string>(
    'reviews/mutations:updateWidgetSettings',
    {
      userId,
      businessName: input.businessName ?? undefined,
      businessNameAr: input.businessNameAr ?? undefined,
      logoUrl: input.logoUrl ?? undefined,
      primaryColor: input.primaryColor,
      backgroundColor: input.backgroundColor,
      textColor: input.textColor,
      thankYouMessage: input.thankYouMessage ?? undefined,
      thankYouMessageAr: input.thankYouMessageAr ?? undefined,
      showPoweredBy: input.showPoweredBy,
      customCss: input.customCss ?? undefined,
    },
  );

  log.info('Widget settings upserted', { userId, settingsId: convexId });

  // Return the freshly-saved settings
  return await getWidgetSettings(userId);
}

// ═══════════════════════════════════════════════════════════════════════
// Featured Reviews (Testimonials)
// ═══════════════════════════════════════════════════════════════════════

export async function listFeaturedReviews(userId: string) {
  const reviews = await convexQuery<ConvexReview[]>(
    'reviews/queries:getFeaturedReviews',
    { userId },
  );

  const docs = reviews ?? [];
  log.info('Listed featured reviews', { userId, count: docs.length });

  // Return only public-safe fields, limited to 100
  return docs.slice(0, 100).map((r) => ({
    id: r._id,
    customerName: r.customerName,
    rating: r.rating,
    title: r.title ?? null,
    content: r.content ?? null,
    language: r.language,
    platform: r.platform,
    createdAt: new Date(r.createdAt),
  }));
}

export async function toggleFeaturedReview(
  userId: string,
  reviewId: string,
  featured: boolean,
) {
  // The updateReview mutation verifies ownership and auto-assigns
  // featuredOrder when featuring, so we can call it directly.
  try {
    await convexMutation(
      'reviews/mutations:updateReview',
      {
        userId,
        reviewId: reviewId as unknown as Id<'reviews'>,
        isFeatured: featured,
      },
    );
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    if (message.includes('not found') || message.includes('access denied')) {
      throw new Error('REVIEW_NOT_FOUND');
    }
    throw error;
  }

  log.info('Toggled featured review', { reviewId, userId, featured });
  return { id: reviewId, isFeatured: featured };
}

export async function reorderFeaturedReviews(
  userId: string,
  orderedIds: string[],
) {
  await convexMutation(
    'reviews/mutations:reorderFeaturedReviews',
    {
      userId,
      orderedIds: orderedIds as unknown as Id<'reviews'>[],
    },
  );

  log.info('Reordered featured reviews', { userId, count: orderedIds.length });
}

export async function generateEmbedCode(userId: string) {
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://mawidi.com';
  const embedUrl = `${appUrl}/api/public/testimonials/${userId}`;

  return {
    iframe: `<iframe src="${appUrl}/embed/testimonials/${userId}" width="100%" height="400" frameborder="0" style="border:none;overflow:hidden;" allowtransparency="true"></iframe>`,
    script: `<div id="mawidi-testimonials" data-user-id="${userId}"></div>\n<script src="${appUrl}/embed/testimonials.js" async></script>`,
    apiUrl: embedUrl,
  };
}

export async function getPublicWidgetData(token: string) {
  const request = await convexQuery<ConvexReviewRequest | null>(
    'reviews/queries:getReviewRequestByToken',
    {
      token,
      statuses: ['PENDING', 'SENT'],
      notExpired: true,
    },
  );

  if (!request) {
    log.warn('Public widget data not found for token', { token: token.slice(0, 8) + '...' });
    return null;
  }

  const widgetSettings = await convexQuery<ConvexWidgetSettings | null>(
    'reviews/queries:getWidgetSettings',
    { userId: request.userId },
  );

  return {
    requestId: request._id,
    customerName: request.customerName,
    language: request.language,
    questions: (request.questions as unknown[]) ?? [],
    widget: {
      businessName: widgetSettings?.businessName ?? null,
      businessNameAr: widgetSettings?.businessNameAr ?? null,
      logoUrl: widgetSettings?.logoUrl ?? null,
      primaryColor: widgetSettings?.primaryColor ?? DEFAULT_WIDGET_SETTINGS.primaryColor,
      backgroundColor: widgetSettings?.backgroundColor ?? DEFAULT_WIDGET_SETTINGS.backgroundColor,
      textColor: widgetSettings?.textColor ?? DEFAULT_WIDGET_SETTINGS.textColor,
      thankYouMessage: widgetSettings?.thankYouMessage ?? null,
      thankYouMessageAr: widgetSettings?.thankYouMessageAr ?? null,
      showPoweredBy: widgetSettings?.showPoweredBy ?? true,
      customCss: widgetSettings?.customCss ?? null,
    },
  };
}
