import { apiClient } from "./client";

export interface SmartFactoryLogEntry {
  id: number;
  company_code: string;
  company_name: string | null;
  user_id: string;
  user_name: string | null;
  use_type: string;
  connect_ip: string;
  send_status: "SUCCESS" | "FAIL" | "SKIPPED";
  response_status: number | null;
  error_message: string | null;
  log_dt: string;
  created_at: string;
}

export interface SmartFactoryLogFilters {
  companyCode?: string;
  userId?: string;
  sendStatus?: string;
  dateFrom?: string;
  dateTo?: string;
  search?: string;
  page?: number;
  limit?: number;
}

export interface SmartFactoryLogStats {
  total: number;
  statusCounts: Array<{ status: string; count: number }>;
  companyCounts: Array<{ companyCode: string; companyName: string; count: number }>;
  dailyCounts: Array<{ date: string; count: number }>;
}

export async function getSmartFactoryLogs(
  filters: SmartFactoryLogFilters
): Promise<{
  success: boolean;
  data: SmartFactoryLogEntry[];
  total: number;
  page: number;
  limit: number;
}> {
  const params = new URLSearchParams();
  if (filters.companyCode) params.append("companyCode", filters.companyCode);
  if (filters.userId) params.append("userId", filters.userId);
  if (filters.sendStatus) params.append("sendStatus", filters.sendStatus);
  if (filters.dateFrom) params.append("dateFrom", filters.dateFrom);
  if (filters.dateTo) params.append("dateTo", filters.dateTo);
  if (filters.search) params.append("search", filters.search);
  if (filters.page) params.append("page", String(filters.page));
  if (filters.limit) params.append("limit", String(filters.limit));

  const response = await apiClient.get(`/admin/smart-factory-log?${params.toString()}`);
  return response.data;
}

export async function getSmartFactoryLogStats(
  companyCode?: string,
  days?: number
): Promise<{ success: boolean; data: SmartFactoryLogStats }> {
  const params = new URLSearchParams();
  if (companyCode) params.append("companyCode", companyCode);
  if (days) params.append("days", String(days));

  const response = await apiClient.get(`/admin/smart-factory-log/stats?${params.toString()}`);
  return response.data;
}

// ─── 스케줄 관리 ───

export interface SmartFactorySchedule {
  id: number;
  company_code: string;
  company_name: string | null;
  is_active: boolean;
  time_start: string;
  time_end: string;
  exclude_weekend: boolean;
  exclude_holidays: boolean;
  daily_count: number;
  created_at: string;
  updated_at: string;
}

export interface TodayPlanEntry {
  companyCode: string;
  total: number;
  sent: number;
  remaining: number;
}

export interface SmartFactoryHoliday {
  id: number;
  holiday_date: string;
  holiday_name: string;
  created_at: string;
}

export async function getSchedules(): Promise<{ success: boolean; data: SmartFactorySchedule[] }> {
  const response = await apiClient.get("/admin/smart-factory-log/schedules");
  return response.data;
}

export async function upsertSchedule(params: {
  companyCode: string;
  isActive: boolean;
  timeStart: string;
  timeEnd: string;
  excludeWeekend: boolean;
  excludeHolidays: boolean;
  dailyCount: number;
}): Promise<{ success: boolean; message: string }> {
  const response = await apiClient.post("/admin/smart-factory-log/schedules", params);
  return response.data;
}

export async function deleteSchedule(companyCode: string): Promise<{ success: boolean }> {
  const response = await apiClient.delete(`/admin/smart-factory-log/schedules/${companyCode}`);
  return response.data;
}

export async function runScheduleNow(companyCode: string): Promise<{
  success: boolean;
  data: { total: number; sent: number; skipped: number };
}> {
  const response = await apiClient.post(`/admin/smart-factory-log/schedules/${companyCode}/run-now`);
  return response.data;
}

export async function getTodayPlan(): Promise<{ success: boolean; data: TodayPlanEntry[] }> {
  const response = await apiClient.get("/admin/smart-factory-log/schedules/today-plan");
  return response.data;
}

export async function getHolidays(): Promise<{ success: boolean; data: SmartFactoryHoliday[] }> {
  const response = await apiClient.get("/admin/smart-factory-log/holidays");
  return response.data;
}

export async function addHoliday(holidayDate: string, holidayName: string): Promise<{ success: boolean }> {
  const response = await apiClient.post("/admin/smart-factory-log/holidays", { holidayDate, holidayName });
  return response.data;
}

export async function deleteHoliday(id: number): Promise<{ success: boolean }> {
  const response = await apiClient.delete(`/admin/smart-factory-log/holidays/${id}`);
  return response.data;
}

// ─── API 키 관리 ───

export interface ApiKeyEntry {
  companyCode: string;
  companyName: string;
  hasDbKey: boolean;
  dbKey: string | null;
  hasEnvKey: boolean;
}

export async function getApiKeys(): Promise<{ success: boolean; data: ApiKeyEntry[] }> {
  const response = await apiClient.get("/admin/smart-factory-log/api-keys");
  return response.data;
}

export async function saveApiKey(companyCode: string, apiKey: string): Promise<{ success: boolean }> {
  const response = await apiClient.post("/admin/smart-factory-log/api-keys", { companyCode, apiKey });
  return response.data;
}

export async function deleteApiKey(companyCode: string): Promise<{ success: boolean }> {
  const response = await apiClient.delete(`/admin/smart-factory-log/api-keys/${companyCode}`);
  return response.data;
}

// ─── 즉시 전송 ───

export interface CompanyUser {
  user_id: string;
  user_name: string;
  dept_name: string | null;
}

export async function getCompanyUsers(companyCode: string): Promise<{ success: boolean; data: CompanyUser[] }> {
  const response = await apiClient.get(`/admin/smart-factory-log/users/${companyCode}`);
  return response.data;
}

export async function sendNow(params: {
  companyCode: string;
  userIds: string[];
  timeStart?: string;
  timeEnd?: string;
}): Promise<{ success: boolean; data: { total: number }; message: string }> {
  const response = await apiClient.post("/admin/smart-factory-log/send-now", params);
  return response.data;
}
