/**
 * 自动提现配置API
 */

import { NextRequest, NextResponse } from 'next/server';

// 内存存储（实际应用中应该存入数据库）
const autoWithdrawConfigs: Map<string, {
  userId: string;
  enabled: boolean;
  minAmount: number;
  method: 'wechat' | 'alipay';
  account: string;
  name: string;
  createdAt: string;
  updatedAt: string;
}> = new Map();

// GET: 获取用户自动提现配置
export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const userId = searchParams.get('userId');

  if (!userId) {
    return NextResponse.json({ error: '缺少用户ID' }, { status: 400 });
  }

  const config = autoWithdrawConfigs.get(userId);
  
  return NextResponse.json({
    success: true,
    config: config || null,
  });
}

// POST: 保存/更新自动提现配置
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { userId, enabled, minAmount, method, account, name } = body;

    if (!userId) {
      return NextResponse.json({ error: '缺少用户ID' }, { status: 400 });
    }

    // 验证参数
    if (enabled) {
      if (!minAmount || minAmount < 10) {
        return NextResponse.json({ error: '最低提现金额不能少于10元' }, { status: 400 });
      }
      if (!account) {
        return NextResponse.json({ error: '请填写提现账号' }, { status: 400 });
      }
      if (!name) {
        return NextResponse.json({ error: '请填写真实姓名' }, { status: 400 });
      }
    }

    const now = new Date().toISOString();
    const existingConfig = autoWithdrawConfigs.get(userId);

    const config = {
      userId,
      enabled: Boolean(enabled),
      minAmount: Number(minAmount) || 100,
      method: method || 'wechat',
      account: account || '',
      name: name || '',
      createdAt: existingConfig?.createdAt || now,
      updatedAt: now,
    };

    autoWithdrawConfigs.set(userId, config);

    console.log('[AutoWithdrawConfig] 保存配置:', {
      userId,
      enabled: config.enabled,
      minAmount: config.minAmount,
      method: config.method,
    });

    return NextResponse.json({
      success: true,
      config,
      message: enabled ? '自动提现已启用' : '自动提现已关闭',
    });
  } catch (error) {
    console.error('[AutoWithdrawConfig] 保存失败:', error);
    return NextResponse.json({ error: '保存配置失败' }, { status: 500 });
  }
}

// DELETE: 删除自动提现配置
export async function DELETE(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const userId = searchParams.get('userId');

  if (!userId) {
    return NextResponse.json({ error: '缺少用户ID' }, { status: 400 });
  }

  autoWithdrawConfigs.delete(userId);

  return NextResponse.json({
    success: true,
    message: '配置已删除',
  });
}
