/*
 * M12 EDM·캠페인 · 스폰서십 실 API 계약 (SCR-33·SCR-34).
 * 공용 클라이언트(../../api/client)만 사용 — client.ts·endpoints.ts 무수정.
 *
 * 백엔드 컨트롤러 정본:
 *   GET  /api/events/{eventId}/campaigns?status → ApiResponse<CampaignDto[]>
 *   POST /api/events/{eventId}/campaigns (생성 — status 전이만)
 *   POST /api/events/{eventId}/campaigns/{id}/send (수신동의자 한정 실 발송)
 *   GET  /api/events/{eventId}/sponsorship → ApiResponse<SponsorshipView>
 */
import { api } from '../../api/client';

// ── SCR-33 캠페인 ──
export interface CampaignDto {
  id: string;
  name: string;
  status: string; // draft|scheduled|sending|done
  audience: number;
  meta: string | null;
  openRate: string | null;
  clickRate: string | null;
}
export interface CampaignCreateBody {
  name: string;
  audience?: number;
  meta?: string;
  scheduleType?: 'now' | 'later';
  scheduledAt?: string;
}

// ── SCR-34 스폰서십 ──
export interface MktKpiDto {
  label: string;
  value: string;
  unit: string | null;
  tone: string | null;
}
export interface TierDto {
  id: string;
  name: string;
  nameKo: string;
  price: string;
  accent: string | null;
  benefits: string[];
  remaining: number;
  status: string; // available|soldout
  dday: number | null;
}
export interface FulfillmentDto {
  id: string;
  label: string;
  done: boolean;
}
export interface SponsorDto {
  id: string;
  name: string;
  initial: string;
  tier: string | null;
  status: string; // signed|pending
  fulfillment: FulfillmentDto[];
}
export interface SponsorshipViewDto {
  kpis: MktKpiDto[];
  tiers: TierDto[];
  sponsors: SponsorDto[];
}

// ── 캠페인 발송 결과(집계) ──
export interface CampaignSendResultDto {
  id: string;
  status: string; // draft|scheduled|sending|done
  testMode: boolean; // 실 수신자 미발송(테스트/드라이런)
  mailEnabled: boolean;
  eligible: number; // 수신동의·미거부 대상 총수
  sentCount: number; // 실제 디스패치 건수
  skipped: number; // 상한/rate cap/무효 스킵
  failed: number; // 동기 검증 실패(SMTP 비동기 실패는 이력)
  meta: string;
}

export const marketingApi = {
  campaigns: (eventId: string, status?: string) => {
    const qs = status ? `?status=${encodeURIComponent(status)}` : '';
    return api.get<CampaignDto[]>(`/api/events/${encodeURIComponent(eventId)}/campaigns${qs}`);
  },
  createCampaign: (eventId: string, body: CampaignCreateBody) =>
    api.post<CampaignDto>(`/api/events/${encodeURIComponent(eventId)}/campaigns`, body),
  // live=true 는 운영 실발송(서버 EDM_TEST_MODE=false 필요). 미지정/false 는 안전 기본(테스트 모드).
  sendCampaign: (eventId: string, id: string, live?: boolean) =>
    api.post<CampaignSendResultDto>(
      `/api/events/${encodeURIComponent(eventId)}/campaigns/${encodeURIComponent(id)}/send`,
      { live: live ?? false },
    ),
  sponsorship: (eventId: string) =>
    api.get<SponsorshipViewDto>(`/api/events/${encodeURIComponent(eventId)}/sponsorship`),
};
