import { NextResponse } from 'next/server';
import { db } from '@/db/connection';
import { employees, branches } from '@/db/schema';
import { eq, count } from 'drizzle-orm';
import { getAuthUser, generateId } from '@/lib/auth';

// Helper: check admin access
function checkAdmin(request: Request) {
  const user = getAuthUser(request);
  if (!user) {
    return NextResponse.json(
      { success: false, error: 'กรุณาเข้าสู่ระบบ' },
      { status: 401 }
    );
  }
  if (!user.isAdmin) {
    return NextResponse.json(
      { success: false, error: 'ไม่มีสิทธิ์เข้าถึง' },
      { status: 403 }
    );
  }
  return null;
}

// ==================== GET /api/admin/branches ====================
export async function GET(request: Request) {
  try {
    const authError = checkAdmin(request);
    if (authError) return authError;

    // Get all branches with employee count
    const branchesWithCount = await db
      .select({
        id: branches.id,
        name: branches.name,
        code: branches.code,
        createdAt: branches.createdAt,
        employeeCount: count(employees.id),
      })
      .from(branches)
      .leftJoin(employees, eq(branches.id, employees.branchId))
      .groupBy(branches.id);

    return NextResponse.json({
      success: true,
      branches: branchesWithCount,
    });
  } catch (error) {
    console.error('GET /api/admin/branches error:', error);
    return NextResponse.json(
      { success: false, error: 'เกิดข้อผิดพลาดในระบบ' },
      { status: 500 }
    );
  }
}

// ==================== POST /api/admin/branches ====================
export async function POST(request: Request) {
  try {
    const authError = checkAdmin(request);
    if (authError) return authError;

    const body = await request.json();
    const { name, code } = body as { name?: string; code?: string };

    if (!name || !code) {
      return NextResponse.json(
        { success: false, error: 'กรุณาระบุชื่อและรหัสสาขา' },
        { status: 400 }
      );
    }

    // Check if code already exists
    const existing = await db
      .select({ id: branches.id })
      .from(branches)
      .where(eq(branches.code, code))
      .limit(1);

    if (existing.length > 0) {
      return NextResponse.json(
        { success: false, error: 'รหัสสาขานี้มีอยู่ในระบบแล้ว' },
        { status: 400 }
      );
    }

    const id = generateId();
    await db.insert(branches).values({
      id,
      name,
      code,
      createdAt: new Date(),
    });

    const created = await db
      .select()
      .from(branches)
      .where(eq(branches.id, id))
      .limit(1);

    return NextResponse.json({
      success: true,
      branch: created[0],
    });
  } catch (error) {
    console.error('POST /api/admin/branches error:', error);
    return NextResponse.json(
      { success: false, error: 'เกิดข้อผิดพลาดในระบบ' },
      { status: 500 }
    );
  }
}
