import { http } from '../api';
import { commonApi } from '../api';

export type NotificationType = 'step_completed' | 'plan_created' | 'plan_updated' | 'inventory_in' | 'payment_pending' | 'system';

interface NotificationData {
  recipient_id: string;
  sender_id?: string;
  sender_company_id?: string;
  plan_id?: string;
  type: NotificationType;
  title: string;
  content: string;
}

export async function sendNotification(data: NotificationData): Promise<void> {
  try {
    await http.post('/common/notifications', {
      recipient_id: data.recipient_id,
      sender_id: data.sender_id,
      sender_company_id: data.sender_company_id,
      plan_id: data.plan_id,
      type: data.type,
      title: data.title,
      content: data.content
    });
  } catch {
  }
}

export async function getPlanPurchaserUserId(planId: string): Promise<string | null> {
  try {
    const { data: plan } = await http.get<any>(`/common/plans/${planId}/purchaser`);
    if (!plan) return null;
    return plan.user_id || null;
  } catch {
    return null;
  }
}

export async function getPlanFactoryUserIds(planId: string, factoryType?: 'textile' | 'washing'): Promise<string[]> {
  try {
    const params: Record<string, string> = {};
    if (factoryType) params.factory_type = factoryType;
    const { data } = await http.get<any[]>(`/common/plans/${planId}/factory-users`, params);
    return (data || []).map(p => p.id);
  } catch {
    return [];
  }
}

export async function notifyStepCompleted(
  planId: string,
  stepName: string,
  senderCompanyId: string,
  senderUserId: string,
  details?: { quantity?: number; rolls?: number }
): Promise<void> {
  try {
    await http.post(`/common/plans/${planId}/notify/step-completed`, {
      step_name: stepName,
      sender_company_id: senderCompanyId,
      sender_user_id: senderUserId,
      details
    });
  } catch {
  }
}

export async function notifyInventoryIn(
  planId: string,
  quantity: number,
  rolls: number,
  senderCompanyId: string,
  senderUserId: string
): Promise<void> {
  await notifyStepCompleted(planId, '坯布入库', senderCompanyId, senderUserId, { quantity, rolls });
}

export async function notifyPlanCreated(
  planId: string,
  factoryIds: string[],
  senderCompanyId: string,
  senderUserId: string
): Promise<void> {
  try {
    await http.post(`/common/plans/${planId}/notify/created`, {
      factory_ids: factoryIds,
      sender_company_id: senderCompanyId,
      sender_user_id: senderUserId
    });
  } catch {
  }
}

export async function notifyPlanUpdated(
  planId: string,
  status: string,
  senderCompanyId: string,
  senderUserId: string
): Promise<void> {
  try {
    await http.post(`/common/plans/${planId}/notify/updated`, {
      status,
      sender_company_id: senderCompanyId,
      sender_user_id: senderUserId
    });
  } catch {
  }
}
