import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';
import { createHash } from 'crypto';
import { loginAdminSchema } from '@/storage/database/shared/schema';

// POST /api/admin/login - 管理员登录
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证请求数据
    const validationResult = loginAdminSchema.safeParse(body);
    if (!validationResult.success) {
      return NextResponse.json(
        { error: '数据验证失败', details: validationResult.error.issues },
        { status: 400 }
      );
    }
    
    const { username, password } = validationResult.data;
    const passwordHash = createHash('sha256').update(password).digest('hex');
    
    const client = getSupabaseClient();
    
    // 查询管理员
    const { data: admin, error } = await client
      .from('admins')
      .select('id, username, name, role, is_active')
      .eq('username', username)
      .eq('password', passwordHash)
      .eq('is_active', true)
      .single();
    
    if (error || !admin) {
      return NextResponse.json(
        { error: '用户名或密码错误' },
        { status: 401 }
      );
    }
    
    // 创建响应并设置cookie
    const response = NextResponse.json({
      success: true,
      admin: {
        id: admin.id,
        username: admin.username,
        name: admin.name,
        role: admin.role,
      }
    });
    
    // 设置管理员会话cookie (有效期7天)
    response.cookies.set('admin_id', admin.id, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7, // 7天
      path: '/',
    });
    
    response.cookies.set('admin_name', admin.name, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });
    
    response.cookies.set('admin_role', admin.role, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });
    
    return response;
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
