/**
 * Social Media Validators
 * Zod validation schemas for social content pipeline
 */

import { z } from 'zod';
import { PLATFORM_LIMITS, type SocialPlatform } from '@/lib/types/social-media.types';

// Platform enum schema
export const socialPlatformSchema = z.enum(['INSTAGRAM', 'FACEBOOK', 'TIKTOK', 'TWITTER']);

// Integration status schema
export const socialIntegrationStatusSchema = z.enum([
  'CONNECTED',
  'DISCONNECTED',
  'TOKEN_EXPIRED',
  'ERROR',
]);

// Queue status schema
export const socialQueueStatusSchema = z.enum([
  'DRAFT',
  'SCHEDULED',
  'PUBLISHING',
  'PUBLISHED',
  'FAILED',
]);

// AI content type schema
export const aiContentTypeSchema = z.enum(['BLOG', 'SOCIAL_POST', 'IMAGE']);

// Blog generation input schema
export const blogGenerationInputSchema = z.object({
  topic: z.string().min(3, 'Topic must be at least 3 characters').max(200, 'Topic too long'),
  keywords: z.array(z.string().max(50)).max(10).optional(),
  tone: z.enum(['professional', 'casual', 'informative']),
  language: z.enum(['ar', 'en']),
  wordCount: z.number().min(300).max(3000).optional().default(1000),
});

// Social account create schema
export const socialAccountCreateSchema = z.object({
  platform: socialPlatformSchema,
  platformAccountId: z.string().min(1, 'Platform account ID required'),
  accountName: z.string().min(1, 'Account name required').max(100),
  accessToken: z.string().min(1, 'Access token required'),
  refreshToken: z.string().optional(),
  tokenExpiry: z.coerce.date().optional(),
  metadata: z.record(z.unknown()).optional(),
});

// Social account update schema
export const socialAccountUpdateSchema = z.object({
  accessToken: z.string().min(1).optional(),
  refreshToken: z.string().optional(),
  tokenExpiry: z.coerce.date().optional(),
  status: socialIntegrationStatusSchema.optional(),
  metadata: z.record(z.unknown()).optional(),
});

// Helper: Create platform-specific content schema
export function createPlatformContentSchema(platform: SocialPlatform) {
  const limits = PLATFORM_LIMITS[platform];
  return z.object({
    content: z
      .string()
      .min(1, 'Content is required')
      .max(limits.maxChars, `Content exceeds ${limits.name} limit of ${limits.maxChars} characters`),
    hashtags: z
      .array(z.string().regex(/^#?[\w]+$/, 'Invalid hashtag format'))
      .max(limits.maxHashtags, `Maximum ${limits.maxHashtags} hashtags for ${limits.name}`),
    mediaUrls: limits.mediaRequired
      ? z.array(z.string().url()).min(1, `${limits.name} requires at least one media file`)
      : z.array(z.string().url()),
    platform: z.literal(platform),
  });
}

// Social post schema (generic, validates platform-specific limits dynamically)
export const socialPostSchema = z
  .object({
    content: z.string().min(1, 'Content is required'),
    hashtags: z.array(z.string()),
    mediaUrls: z.array(z.string().url()),
    platform: socialPlatformSchema,
  })
  .refine(
    (data) => {
      const limits = PLATFORM_LIMITS[data.platform];
      return data.content.length <= limits.maxChars;
    },
    {
      message: 'Content exceeds platform character limit',
      path: ['content'],
    }
  )
  .refine(
    (data) => {
      const limits = PLATFORM_LIMITS[data.platform];
      return data.hashtags.length <= limits.maxHashtags;
    },
    {
      message: 'Too many hashtags for this platform',
      path: ['hashtags'],
    }
  )
  .refine(
    (data) => {
      const limits = PLATFORM_LIMITS[data.platform];
      if (limits.mediaRequired && data.mediaUrls.length === 0) {
        return false;
      }
      return true;
    },
    {
      message: 'This platform requires at least one media file',
      path: ['mediaUrls'],
    }
  );

// Queue item create schema
export const queueItemCreateSchema = z.object({
  blogPostId: z.string().cuid().optional(),
  socialAccountId: z.string().cuid({ message: 'Valid social account ID required' }),
  platform: socialPlatformSchema,
  content: z.string().min(1, 'Content is required'),
  hashtags: z.array(z.string()).optional().default([]),
  mediaUrls: z.array(z.string().url()).optional().default([]),
  scheduledAt: z.coerce.date().optional(),
});

// Queue item update schema
export const queueItemUpdateSchema = z.object({
  content: z.string().min(1).optional(),
  hashtags: z.array(z.string()).optional(),
  mediaUrls: z.array(z.string().url()).optional(),
  status: socialQueueStatusSchema.optional(),
  scheduledAt: z.coerce.date().nullable().optional(),
});

// OAuth callback schema
export const oauthCallbackSchema = z.object({
  code: z.string().min(1, 'Authorization code required'),
  state: z.string().min(1, 'State parameter required'),
});

// OAuth state schema (for validation when decoding)
export const oauthStateSchema = z.object({
  userId: z.string().min(1),
  platform: socialPlatformSchema,
  csrfToken: z.string().min(32),
  redirectUrl: z.string().url(),
  timestamp: z.number(),
});

// ═══════════════════════════════════════════════════════════════════════
// Social Inbox Validators (Enterprise / tier4)
// ═══════════════════════════════════════════════════════════════════════

export const socialMessageDirectionSchema = z.enum(['INBOUND', 'OUTBOUND']);
export const socialTrendTypeSchema = z.enum(['HASHTAG', 'TOPIC', 'ENGAGEMENT_PATTERN', 'BEST_TIME']);

export const inboxReplySchema = z.object({
  content: z.string().min(1, 'Reply content required').max(10000),
  mediaUrls: z.array(z.string().url()).max(10).optional().default([]),
});

export const inboxMarkReadSchema = z.object({
  messageIds: z.array(z.string()).min(1).max(100).optional(),
  conversationId: z.string().optional(),
}).refine(
  (data) => data.messageIds || data.conversationId,
  { message: 'Either messageIds or conversationId required' }
);

// ═══════════════════════════════════════════════════════════════════════
// AI Assistant Validators
// ═══════════════════════════════════════════════════════════════════════

export const aiGenerateSchema = z.object({
  type: z.enum(['caption', 'hashtags', 'reply', 'rephrase']),
  platform: socialPlatformSchema.optional(),
  topic: z.string().max(500).optional(),
  tone: z.enum(['professional', 'casual', 'friendly', 'witty']).optional().default('professional'),
  language: z.enum(['ar', 'en']).optional().default('en'),
  context: z.string().max(5000).optional(),
  originalContent: z.string().max(10000).optional(),
});

export const aiRephraseSchema = z.object({
  content: z.string().min(1, 'Content required').max(10000),
  tone: z.enum(['professional', 'casual', 'friendly', 'witty']).optional().default('professional'),
  language: z.enum(['ar', 'en']).optional().default('en'),
  platform: socialPlatformSchema.optional(),
});

export const aiReplyDraftSchema = z.object({
  conversationId: z.string().min(1, 'Conversation ID required'),
  tone: z.enum(['professional', 'casual', 'friendly', 'witty']).optional().default('professional'),
  language: z.enum(['ar', 'en']).optional().default('en'),
});

// ═══════════════════════════════════════════════════════════════════════
// Calendar / Scheduling Validators
// ═══════════════════════════════════════════════════════════════════════

export const schedulePostSchema = z.object({
  socialAccountId: z.string().min(1, 'Social account required'),
  platform: socialPlatformSchema,
  content: z.string().min(1, 'Content required'),
  hashtags: z.array(z.string()).optional().default([]),
  mediaUrls: z.array(z.string().url()).optional().default([]),
  scheduledAt: z.coerce.date(),
  calendarColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
  campaignTag: z.string().max(50).optional(),
});

export const bulkScheduleSchema = z.object({
  items: z.array(schedulePostSchema).min(1, 'At least one item required').max(50),
});

export const rescheduleSchema = z.object({
  scheduledAt: z.coerce.date(),
});

export const calendarQuerySchema = z.object({
  month: z.coerce.number().min(1).max(12).optional(),
  year: z.coerce.number().min(2020).max(2030).optional(),
  platform: socialPlatformSchema.optional(),
  status: socialQueueStatusSchema.optional(),
});

// Infer types from schemas
export type BlogGenerationInputValidated = z.infer<typeof blogGenerationInputSchema>;
export type SocialAccountCreateValidated = z.infer<typeof socialAccountCreateSchema>;
export type SocialAccountUpdateValidated = z.infer<typeof socialAccountUpdateSchema>;
export type SocialPostValidated = z.infer<typeof socialPostSchema>;
export type QueueItemCreateValidated = z.infer<typeof queueItemCreateSchema>;
export type QueueItemUpdateValidated = z.infer<typeof queueItemUpdateSchema>;
export type OAuthCallbackValidated = z.infer<typeof oauthCallbackSchema>;
export type OAuthStateValidated = z.infer<typeof oauthStateSchema>;
export type InboxReplyValidated = z.infer<typeof inboxReplySchema>;
export type InboxMarkReadValidated = z.infer<typeof inboxMarkReadSchema>;
export type AIGenerateValidated = z.infer<typeof aiGenerateSchema>;
export type AIRephraseValidated = z.infer<typeof aiRephraseSchema>;
export type AIReplyDraftValidated = z.infer<typeof aiReplyDraftSchema>;
export type SchedulePostValidated = z.infer<typeof schedulePostSchema>;
export type BulkScheduleValidated = z.infer<typeof bulkScheduleSchema>;
export type RescheduleValidated = z.infer<typeof rescheduleSchema>;
export type CalendarQueryValidated = z.infer<typeof calendarQuerySchema>;
