import { supabase } from '../supabase/client';

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> {
  const { error } = await supabase
    .from('notifications')
    .insert({
      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
    });

  if (error) {
    console.error('发送通知失败:', error);
  }
}

/**
 * 获取计划的采购商用户ID
 */
export async function getPlanPurchaserUserId(planId: string): Promise<string | null> {
  const { data: plan } = await supabase
    .from('production_plans')
    .select('purchaser_id, created_by')
    .eq('id', planId)
    .maybeSingle();

  if (!plan) return null;

  // 优先返回创建者，如果没有则返回公司的主账号
  if (plan.created_by) {
    return plan.created_by;
  }

  // 获取公司的主账号
  const { data: profile } = await supabase
    .from('profiles')
    .select('id')
    .eq('company_id', plan.purchaser_id)
    .eq('is_master', true)
    .maybeSingle();

  return profile?.id || null;
}

/**
 * 获取计划的关联工厂用户ID列表
 */
export async function getPlanFactoryUserIds(planId: string, factoryType?: 'textile' | 'washing'): Promise<string[]> {
  let query = supabase
    .from('plan_factories')
    .select('factory_id')
    .eq('plan_id', planId);

  if (factoryType) {
    query = query.eq('factory_type', factoryType);
  }

  const { data: factories } = await query;

  if (!factories || factories.length === 0) return [];

  const factoryIds = factories.map(f => f.factory_id);

  // 获取这些工厂的主账号用户ID
  const { data: profiles } = await supabase
    .from('profiles')
    .select('id')
    .in('company_id', factoryIds)
    .eq('is_master', true);

  return (profiles || []).map(p => p.id);
}

/**
 * 发送流程节点完成通知给采购商
 */
export async function notifyStepCompleted(
  planId: string,
  stepName: string,
  senderCompanyId: string,
  senderUserId: string,
  details?: { quantity?: number; rolls?: number }
): Promise<void> {
  const purchaserId = await getPlanPurchaserUserId(planId);
  if (!purchaserId) return;

  const { data: plan } = await supabase
    .from('production_plans')
    .select('plan_code, product_name, color, fabric_code, color_code')
    .eq('id', planId)
    .maybeSingle();

  if (!plan) return;

  const { data: senderCompany } = await supabase
    .from('companies')
    .select('name')
    .eq('id', senderCompanyId)
    .maybeSingle();

  let title = `生产节点完成: ${stepName}`;
  let content = `计划 ${plan.plan_code} (${plan.fabric_code}-${plan.color_code}) 的"${stepName}"节点已由 ${senderCompany?.name || '工厂'} 确认完成`;

  if (stepName === '坯布生产' && details?.quantity) {
    title = `坯布生产: ${plan.fabric_code}`;
    content = `${senderCompany?.name || '工厂'} 完成入库 ${details.quantity}米`;
    if (details.rolls) {
      content += ` (${details.rolls}匹)`;
    }
  }

  await sendNotification({
    recipient_id: purchaserId,
    sender_id: senderUserId,
    sender_company_id: senderCompanyId,
    plan_id: planId,
    type: 'step_completed',
    title,
    content
  });
}

/**
 * 发送入库通知给采购商
 */
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> {
  const { data: plan } = await supabase
    .from('production_plans')
    .select('plan_code, product_name, color, fabric_code, color_code, target_quantity')
    .eq('id', planId)
    .maybeSingle();

  if (!plan) return;

  const { data: senderCompany } = await supabase
    .from('companies')
    .select('name')
    .eq('id', senderCompanyId)
    .maybeSingle();

  // 获取工厂的主账号用户ID
  const { data: profiles } = await supabase
    .from('profiles')
    .select('id')
    .in('company_id', factoryIds)
    .eq('is_master', true);

  const notifications = (profiles || []).map(profile =>
    sendNotification({
      recipient_id: profile.id,
      sender_id: senderUserId,
      sender_company_id: senderCompanyId,
      plan_id: planId,
      type: 'plan_created',
      title: `新计划关联: ${plan.fabric_code}`,
      content: `${senderCompany?.name || '采购商'} 将您添加为计划 ${plan.plan_code} (${plan.fabric_code}-${plan.color_code}) 的纺织厂，计划产量 ${plan.target_quantity}米`
    })
  );

  await Promise.all(notifications);
}

/**
 * 发送计划状态更新通知
 */
export async function notifyPlanUpdated(
  planId: string,
  status: string,
  senderCompanyId: string,
  senderUserId: string
): Promise<void> {
  const purchaserId = await getPlanPurchaserUserId(planId);
  if (!purchaserId) return;

  const { data: plan } = await supabase
    .from('production_plans')
    .select('plan_code, fabric_code, color_code')
    .eq('id', planId)
    .maybeSingle();

  if (!plan) return;

  const statusText = status === 'completed' ? '已完成' : status === 'producing' ? '生产中' : '待确定';

  await sendNotification({
    recipient_id: purchaserId,
    sender_id: senderUserId,
    sender_company_id: senderCompanyId,
    plan_id: planId,
    type: 'plan_updated',
    title: `计划状态更新: ${plan.fabric_code}`,
    content: `计划 ${plan.plan_code} (${plan.fabric_code}-${plan.color_code}) 状态已更新为"${statusText}"`
  });
}
