export const dynamic = "force-dynamic";
import getDb from '@/lib/db';
import { getUserFromRequest, unauthorizedResponse } from '@/lib/auth';

// GET /api/partners/[id] - 获取单个合作单位
export async function GET(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { id } = await params;
    const db = await getDb();

    const partner = db.prepare('SELECT * FROM partners WHERE id = ? AND is_deleted = 0').get(id);

    if (!partner) {
      return Response.json(
        { error: '合作单位不存在' },
        { status: 404 }
      );
    }

    return Response.json(partner);
  } catch (error) {
    console.error('获取合作单位失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// PUT /api/partners/[id] - 更新合作单位
export async function PUT(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { id } = await params;
    const body = await request.json();
    const { name, short_name, english_name, website, logo, address, description } = body;

    const db = await getDb();

    const existing = db.prepare('SELECT id FROM partners WHERE id = ? AND is_deleted = 0').get(id);
    if (!existing) {
      return Response.json(
        { error: '合作单位不存在' },
        { status: 404 }
      );
    }

    if (!name || !name.trim()) {
      return Response.json(
        { error: '合作单位名称不能为空' },
        { status: 400 }
      );
    }

    db.prepare(
      `UPDATE partners SET name = ?, short_name = ?, english_name = ?, website = ?, logo = ?, address = ?, description = ?
       WHERE id = ?`
    ).run(
      name.trim(),
      short_name || null,
      english_name || null,
      website || null,
      logo || null,
      address || null,
      description || null,
      id
    );

    const updated = db.prepare('SELECT * FROM partners WHERE id = ?').get(id);

    return Response.json(updated);
  } catch (error) {
    console.error('更新合作单位失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// DELETE /api/partners/[id] - 软删除合作单位
export async function DELETE(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { id } = await params;
    const db = await getDb();

    const existing = db.prepare('SELECT id FROM partners WHERE id = ? AND is_deleted = 0').get(id);
    if (!existing) {
      return Response.json(
        { error: '合作单位不存在' },
        { status: 404 }
      );
    }

    db.prepare('UPDATE partners SET is_deleted = 1 WHERE id = ?').run(id);

    return Response.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除合作单位失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
