import { z } from 'zod';

// =============================================================================
// Review Schemas
// =============================================================================

export const CreateReviewSchema = z.object({
  customerName: z.string().min(1, 'Customer name is required').max(200),
  customerEmail: z.string().email('Invalid email').optional().nullable(),
  customerPhone: z.string().min(5).max(20).optional().nullable(),
  platform: z.enum(['google', 'whatsapp', 'manual', 'email', 'website']).default('manual'),
  rating: z.number().int().min(1).max(5),
  title: z.string().max(200).optional().nullable(),
  content: z.string().max(5000).optional().nullable(),
  language: z.enum(['en', 'ar']).default('en'),
});

export const RespondToReviewSchema = z.object({
  reviewId: z.string().min(1, 'Review ID is required'),
  response: z.string().min(1, 'Response is required').max(2000),
});

export const CreateReviewRequestSchema = z.object({
  customerName: z.string().min(1).max(200),
  customerEmail: z.string().email().optional().nullable(),
  customerPhone: z.string().min(5).max(20).optional().nullable(),
  channel: z.enum(['email', 'whatsapp', 'sms']).default('email'),
  message: z.string().max(1000).optional().nullable(),
  language: z.enum(['en', 'ar']).default('en'),
  // Optional enrichment fields for appointment-triggered requests
  bookingId: z.string().optional().nullable(),
  source: z.enum(['manual', 'auto_booking', 'auto_crm']).default('manual'),
  questions: z
    .array(z.object({ questionEn: z.string(), questionAr: z.string().optional() }))
    .optional()
    .nullable(),
});

export const SubmitReviewViaTokenSchema = z.object({
  rating: z.number().int().min(1).max(5),
  title: z.string().max(200).optional().nullable(),
  content: z.string().max(5000).optional().nullable(),
  customerName: z.string().min(1).max(200),
  language: z.enum(['en', 'ar']).default('en'),
});

export const ReviewFilterSchema = z.object({
  platform: z.enum(['google', 'whatsapp', 'manual', 'email', 'website']).optional(),
  minRating: z.coerce.number().int().min(1).max(5).optional(),
  maxRating: z.coerce.number().int().min(1).max(5).optional(),
  hasResponse: z.enum(['true', 'false']).optional(),
  search: z.string().max(200).optional(),
  page: z.coerce.number().int().min(1).optional().default(1),
  limit: z.coerce.number().int().min(1).max(100).optional().default(20),
  sortBy: z.enum(['createdAt', 'rating']).optional().default('createdAt'),
  sortOrder: z.enum(['asc', 'desc']).optional().default('desc'),
});

// =============================================================================
// Bulk Review Request
// =============================================================================

export const BulkReviewRequestSchema = z.object({
  requests: z
    .array(
      z.object({
        customerName: z.string().min(1).max(200),
        customerEmail: z.string().email().optional().nullable(),
        customerPhone: z.string().min(5).max(20).optional().nullable(),
        channel: z.enum(['email', 'whatsapp', 'sms']),
        bookingId: z.string().optional().nullable(),
        customerId: z.string().optional().nullable(),
      })
    )
    .min(1, 'At least one request is required')
    .max(100, 'Maximum 100 requests at a time'),
  message: z.string().max(1000).optional().nullable(),
  language: z.enum(['en', 'ar']).default('en'),
});

// =============================================================================
// Submit Review with Question Responses
// =============================================================================

export const SubmitReviewWithQuestionsSchema = SubmitReviewViaTokenSchema.extend({
  questionResponses: z.array(
    z.object({
      questionEn: z.string(),
      questionAr: z.string().optional(),
      answer: z.string().max(2000),
      rating: z.number().int().min(1).max(5).optional(),
    })
  ).optional().default([]),
});

// =============================================================================
// Featured Review Management
// =============================================================================

export const ToggleFeaturedSchema = z.object({
  reviewId: z.string().min(1, 'Review ID is required'),
  featured: z.boolean(),
});

export const ReorderFeaturedSchema = z.object({
  orderedIds: z.array(z.string().min(1)).min(1, 'At least one ID is required'),
});

// =============================================================================
// Widget Settings
// =============================================================================

/** Returns true when the CSS string contains no HTML/JS injection patterns. */
function isSafeCss(css: string): boolean {
  const lower = css.toLowerCase();
  return (
    !lower.includes('</') &&        // closing tags e.g. </style>
    !lower.includes('javascript:') &&
    !lower.includes('expression(') &&
    !/<[a-z]/i.test(css)            // opening tags e.g. <script, <style, <link
  );
}

export const WidgetSettingsSchema = z.object({
  businessName: z.string().max(200).optional().nullable(),
  businessNameAr: z.string().max(200).optional().nullable(),
  logoUrl: z.string().url().optional().nullable(),
  primaryColor: z.string().regex(/^#[0-9a-fA-F]{6}$/, 'Must be a valid hex color').default('#10b981'),
  backgroundColor: z.string().regex(/^#[0-9a-fA-F]{6}$/, 'Must be a valid hex color').default('#ffffff'),
  textColor: z.string().regex(/^#[0-9a-fA-F]{6}$/, 'Must be a valid hex color').default('#1e293b'),
  thankYouMessage: z.string().max(2000).optional().nullable(),
  thankYouMessageAr: z.string().max(2000).optional().nullable(),
  showPoweredBy: z.boolean().default(true),
  customCss: z
    .string()
    .max(10000)
    .refine(isSafeCss, { message: 'customCss contains disallowed content' })
    .optional()
    .nullable(),
});

// =============================================================================
// AI Question Generation
// =============================================================================

export const GenerateQuestionsSchema = z.object({
  industry: z.string().min(1, 'Industry is required').max(100),
  language: z.enum(['en', 'ar']),
  count: z.number().int().min(1).max(10).default(5),
});

// =============================================================================
// Inferred Types
// =============================================================================

export type CreateReviewInput = z.infer<typeof CreateReviewSchema>;
export type RespondToReviewInput = z.infer<typeof RespondToReviewSchema>;
export type CreateReviewRequestInput = z.infer<typeof CreateReviewRequestSchema>;
export type SubmitReviewViaTokenInput = z.infer<typeof SubmitReviewViaTokenSchema>;
export type ReviewFilterInput = z.infer<typeof ReviewFilterSchema>;
export type BulkReviewRequestInput = z.infer<typeof BulkReviewRequestSchema>;
export type SubmitReviewWithQuestionsInput = z.infer<typeof SubmitReviewWithQuestionsSchema>;
export type ToggleFeaturedInput = z.infer<typeof ToggleFeaturedSchema>;
export type ReorderFeaturedInput = z.infer<typeof ReorderFeaturedSchema>;
export type WidgetSettingsInput = z.infer<typeof WidgetSettingsSchema>;
export type GenerateQuestionsInput = z.infer<typeof GenerateQuestionsSchema>;
