/**
 * Social Media Types
 * Type definitions for social content pipeline
 */

// Define enums manually until Prisma regeneration
// These match the schema in prisma/schema.prisma
export type SocialPlatform = 'INSTAGRAM' | 'FACEBOOK' | 'TIKTOK' | 'TWITTER';
export type SocialIntegrationStatus = 'CONNECTED' | 'DISCONNECTED' | 'TOKEN_EXPIRED' | 'ERROR';
export type SocialQueueStatus = 'DRAFT' | 'SCHEDULED' | 'PUBLISHING' | 'PUBLISHED' | 'FAILED';
export type AIContentType = 'BLOG' | 'SOCIAL_POST' | 'IMAGE';

// Platform configuration
export interface PlatformConfig {
  name: string;
  icon: string;
  maxChars: number;
  maxHashtags: number;
  mediaRequired: boolean;
  oauthUrl: string;
  scopes: string[];
}

// Platform limits constant
export const PLATFORM_LIMITS: Record<SocialPlatform, PlatformConfig> = {
  INSTAGRAM: {
    name: 'Instagram',
    icon: 'instagram',
    maxChars: 2200,
    maxHashtags: 30,
    mediaRequired: true,
    oauthUrl: 'https://www.facebook.com/v19.0/dialog/oauth',
    scopes: ['instagram_content_publish', 'pages_read_engagement'],
  },
  FACEBOOK: {
    name: 'Facebook',
    icon: 'facebook',
    maxChars: 63206,
    maxHashtags: 30,
    mediaRequired: false,
    oauthUrl: 'https://www.facebook.com/v19.0/dialog/oauth',
    scopes: ['pages_manage_posts', 'pages_read_engagement'],
  },
  TWITTER: {
    name: 'Twitter / X',
    icon: 'twitter',
    maxChars: 280,
    maxHashtags: 5,
    mediaRequired: false,
    oauthUrl: 'https://twitter.com/i/oauth2/authorize',
    scopes: ['tweet.write', 'offline.access', 'users.read'],
  },
  TIKTOK: {
    name: 'TikTok',
    icon: 'tiktok',
    maxChars: 4000,
    maxHashtags: 100,
    mediaRequired: true, // Video required
    oauthUrl: 'https://www.tiktok.com/v2/auth/authorize/',
    scopes: ['video.publish'],
  },
};

// Account types
export interface SocialAccountInput {
  platform: SocialPlatform;
  platformAccountId: string;
  accountName: string;
  accessToken: string;
  refreshToken?: string;
  tokenExpiry?: Date;
  metadata?: Record<string, unknown>;
}

export interface SocialAccountOutput {
  id: string;
  userId: string;
  platform: SocialPlatform;
  platformAccountId: string;
  accountName: string;
  status: SocialIntegrationStatus;
  tokenExpiry: Date | null;
  metadata: Record<string, unknown> | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface TokenData {
  accessToken: string;
  refreshToken?: string;
  expiresIn?: number;
  expiresAt?: Date;
}

// Blog generation types
export interface BlogGenerationInput {
  topic: string;
  keywords?: string[];
  tone: 'professional' | 'casual' | 'informative';
  language: 'ar' | 'en';
  wordCount?: number;
}

export interface BlogGenerationOutput {
  title: string;
  slug: string;
  excerpt: string;
  content: string; // Markdown
  tags: string[];
  seo: {
    metaTitle: string;
    metaDescription: string;
    keywords: string[];
  };
  suggestedCoverImagePrompt: string;
}

// Social post types
export interface SocialPost {
  content: string;
  hashtags: string[];
  mediaUrls: string[];
  platform: SocialPlatform;
}

export interface SocialAdaptation {
  platform: SocialPlatform;
  content: string;
  hashtags: string[];
  characterCount: number;
  isValid: boolean;
  warnings: string[];
}

// Queue types
export interface QueueItemInput {
  blogPostId?: string;
  socialAccountId: string;
  platform: SocialPlatform;
  content: string;
  hashtags?: string[];
  mediaUrls?: string[];
  scheduledAt?: Date;
}

export interface QueueItemOutput {
  id: string;
  blogPostId: string | null;
  socialAccountId: string;
  platform: SocialPlatform;
  content: string;
  hashtags: string[];
  mediaUrls: string[];
  status: SocialQueueStatus;
  scheduledAt: Date | null;
  publishedAt: Date | null;
  platformPostId: string | null;
  platformUrl: string | null;
  retryCount: number;
  errorMessage: string | null;
  createdAt: Date;
  updatedAt: Date;
}

// Post result types
export interface PostResult {
  success: boolean;
  platformPostId?: string;
  platformUrl?: string;
  error?: string;
  retryable?: boolean;
}

// Analytics types
export interface SocialMetrics {
  impressions: number;
  likes: number;
  comments: number;
  shares: number;
  clicks: number;
  engagementRate?: number;
}

export interface AnalyticsOutput extends SocialMetrics {
  id: string;
  queueItemId: string;
  fetchedAt: Date;
}

// OAuth state types
export interface OAuthState {
  userId: string;
  platform: SocialPlatform;
  csrfToken: string;
  redirectUrl: string;
  timestamp: number;
}

// API response types
export interface SocialApiResponse<T = unknown> {
  success: boolean;
  data?: T;
  error?: string;
  message?: string;
}

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

export type SocialMessageDirection = 'INBOUND' | 'OUTBOUND';
export type SocialTrendType = 'HASHTAG' | 'TOPIC' | 'ENGAGEMENT_PATTERN' | 'BEST_TIME';

export interface SocialMessageOutput {
  id: string;
  socialAccountId: string;
  platform: SocialPlatform;
  direction: SocialMessageDirection;
  conversationId: string;
  externalMessageId: string | null;
  senderName: string | null;
  senderHandle: string | null;
  senderAvatarUrl: string | null;
  content: string;
  mediaUrls: string[];
  isRead: boolean;
  threadId: string | null;
  parentMessageId: string | null;
  metadata: Record<string, unknown> | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface InboxConversation {
  conversationId: string;
  platform: SocialPlatform;
  accountName: string;
  lastMessage: SocialMessageOutput;
  unreadCount: number;
  participantName: string | null;
  participantHandle: string | null;
  participantAvatarUrl: string | null;
}

export interface InboxReplyInput {
  content: string;
  mediaUrls?: string[];
}

export interface UnreadCounts {
  total: number;
  byPlatform: Record<SocialPlatform, number>;
  byAccount: Record<string, number>;
}

// ═══════════════════════════════════════════════════════════════════════
// AI Assistant Types
// ═══════════════════════════════════════════════════════════════════════

export interface AIGenerateInput {
  type: 'caption' | 'hashtags' | 'reply' | 'rephrase';
  platform?: SocialPlatform;
  topic?: string;
  tone?: 'professional' | 'casual' | 'friendly' | 'witty';
  language?: 'ar' | 'en';
  context?: string;
  originalContent?: string;
}

export interface AIGenerateOutput {
  content: string;
  hashtags?: string[];
  alternatives?: string[];
  platform?: SocialPlatform;
}

// ═══════════════════════════════════════════════════════════════════════
// Trends Types
// ═══════════════════════════════════════════════════════════════════════

export interface SocialTrendOutput {
  id: string;
  userId: string;
  platform: SocialPlatform | null;
  trendType: SocialTrendType;
  title: string;
  description: string | null;
  score: number;
  hashtags: string[];
  metadata: Record<string, unknown> | null;
  expiresAt: Date;
  createdAt: Date;
}

export interface EngagementPattern {
  dayOfWeek: number;
  hour: number;
  engagementScore: number;
}

export interface PostIdea {
  title: string;
  description: string;
  hashtags: string[];
  bestPlatform: SocialPlatform;
  bestTime: string;
}

export interface BestTimeSlot {
  dayOfWeek: number;
  dayName: string;
  hour: number;
  timeLabel: string;
  score: number;
}

// ═══════════════════════════════════════════════════════════════════════
// Calendar Types
// ═══════════════════════════════════════════════════════════════════════

export interface CalendarEvent {
  id: string;
  title: string;
  platform: SocialPlatform;
  accountName: string;
  status: SocialQueueStatus;
  scheduledAt: Date | null;
  content: string;
  hashtags: string[];
  mediaUrls: string[];
  calendarColor: string | null;
  campaignTag: string | null;
}

export interface ScheduleInput {
  socialAccountId: string;
  platform: SocialPlatform;
  content: string;
  hashtags?: string[];
  mediaUrls?: string[];
  scheduledAt: Date;
  calendarColor?: string;
  campaignTag?: string;
}

export interface BulkScheduleInput {
  items: ScheduleInput[];
}

export interface RescheduleInput {
  scheduledAt: Date;
}
