// 每日简报 API

import { request, type ApiResponse } from './client';

// ========== 类型定义 ==========

export interface WeatherData {
  location: string;
  temp: number;
  condition: string;
  icon: string;
}

export interface NewsItem {
  title: string;
  url: string;
  source: string;
  summary: string;
}

export interface BriefReminder {
  id: string;
  title: string;
  remind_at: string;
}

export interface Briefing {
  id: string;
  user_id: string;
  date: string; // YYYY-MM-DD
  weather?: WeatherData;
  news: NewsItem[];
  reminders: BriefReminder[];
  summary: string;
  summary_source: 'ai' | 'fallback';
  status: 'pending' | 'generated' | 'delivered';
  generated_at?: string;
  delivered_at?: string;
  created_at: string;
}

export interface GenerateBriefingResponse {
  success: boolean;
  briefing?: Briefing;
  message?: string;
  error?: string;
}

// ========== API 方法 ==========

/** 获取指定日期简报 */
export async function getBriefing(userId: string, date: string): Promise<ApiResponse<{ briefing: Briefing | null; message?: string }>> {
  return request(`/briefings?user_id=${encodeURIComponent(userId)}&date=${encodeURIComponent(date)}`);
}

/** 获取最近简报列表 */
export async function getLatestBriefings(userId: string, limit = 7): Promise<ApiResponse<{ briefings: Briefing[]; total: number }>> {
  return request(`/briefings/latest?user_id=${encodeURIComponent(userId)}&limit=${limit}`);
}

/** 手动生成今日简报 */
export async function generateBriefing(userId: string): Promise<ApiResponse<GenerateBriefingResponse>> {
  return request('/briefings/generate', {
    method: 'POST',
    body: { user_id: userId },
  });
}

/** 格式化日期 */
export function formatBriefingDate(date: string): string {
  try {
    const d = new Date(date + 'T00:00:00');
    return d.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      weekday: 'long',
    });
  } catch {
    return date;
  }
}
