import { z } from 'zod';

// ── Delivery Channels ────────────────────────────────────────

export type DeliveryChannel = 'email' | 'telegram' | 'slack' | 'push_apns' | 'push_fcm' | 'sms';
export type DeliveryStatus = 'pending' | 'sent' | 'failed' | 'bounced';

// ── Email Template ───────────────────────────────────────────

export interface EmailTemplate {
  id: string;
  name: string;
  subject: string;
  bodyHtml: string;
  bodyText: string;
  variables: string[];
}

// ── Delivery Request ─────────────────────────────────────────

export const SendEmailSchema = z.object({
  to: z.string().email(),
  templateId: z.string().min(1),
  variables: z.record(z.string()).default({}),
  productId: z.string().min(1),
});

export const SendPushSchema = z.object({
  userId: z.string().min(1),
  title: z.string().min(1),
  body: z.string().min(1),
  data: z.record(z.unknown()).optional(),
  productId: z.string().min(1),
});

export const SendTelegramSchema = z.object({
  text: z.string().min(1),
  productId: z.string().min(1),
  chatId: z.string().min(1).optional(),
  disableNotification: z.boolean().optional(),
});

export const SendSlackSchema = z.object({
  text: z.string().min(1),
  productId: z.string().min(1),
  channel: z.string().min(1).optional(),
  username: z.string().min(1).optional(),
});

export const SendTestEmailSchema = z.object({
  to: z.string().email(),
  templateId: z.string().min(1),
  variables: z.record(z.string()).default({}),
});

export type SendEmailInput = z.infer<typeof SendEmailSchema>;
export type SendPushInput = z.infer<typeof SendPushSchema>;
export type SendTelegramInput = z.infer<typeof SendTelegramSchema>;
export type SendSlackInput = z.infer<typeof SendSlackSchema>;

// ── Delivery Log ─────────────────────────────────────────────

export interface DeliveryLogDoc {
  id: string;
  productId: string;
  pk: string;
  userId?: string;
  channel: DeliveryChannel;
  templateId?: string;
  to: string;
  subject?: string;
  status: DeliveryStatus;
  sentAt?: string;
  error?: string;
  metadata?: Record<string, unknown>;
  createdAt: string;
  _ts?: number;
}

// ── Channel Config ───────────────────────────────────────────

export interface EmailChannelConfig {
  provider: 'smtp' | 'sendgrid' | 'postmark' | 'bytelyst' | 'console';
  apiKey?: string;
  fromEmail: string;
  fromName: string;
  smtpHost?: string;
  smtpPort?: number;
  smtpSecure?: boolean;
  smtpUser?: string;
  smtpPassword?: string;
}

export interface PushChannelConfig {
  apns?: { teamId: string; keyId: string; key: string; bundleId: string };
  fcm?: { projectId: string; serviceAccountKey: string };
}

export interface TelegramChannelConfig {
  botToken?: string;
  defaultChatId?: string;
}

export interface SlackChannelConfig {
  webhookUrl?: string;
  defaultChannel?: string;
}
