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

// GET /api/partners - 获取合作单位列表
export async function GET(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { searchParams } = new URL(request.url);
    const search = searchParams.get('search');

    const db = await getDb();

    let sql = 'SELECT * FROM partners WHERE is_deleted = 0';
    const queryParams = [];

    if (search && search.trim()) {
      sql += ' AND (name LIKE ? OR short_name LIKE ?)';
      const keyword = `%${search.trim()}%`;
      queryParams.push(keyword, keyword);
    }

    sql += ' ORDER BY id DESC';

    const partners = db.prepare(sql).all(...queryParams);

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

// POST /api/partners - 创建合作单位
export async function POST(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

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

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

    const db = await getDb();

    const result = db.prepare(
      'INSERT INTO partners (name, short_name, english_name, website, logo, address, description) VALUES (?, ?, ?, ?, ?, ?, ?)'
    ).run(
      name.trim(),
      short_name || null,
      english_name || null,
      website || null,
      logo || null,
      address || null,
      description || null
    );

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

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