import { NextResponse } from 'next/server';
import { db } from '@/db/connection';
import { employees, branches } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { getAuthUser, generateId, hashPin } 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;
}

// Helper: strip pin from employee record
function stripPin(employee: Record<string, unknown>) {
  const { pin, ...rest } = employee;
  return rest;
}

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

    // Get all employees with branch info (exclude pin)
    const employeeList = await db
      .select({
        id: employees.id,
        employeeId: employees.employeeId,
        name: employees.name,
        branchId: employees.branchId,
        isAdmin: employees.isAdmin,
        isActive: employees.isActive,
        createdAt: employees.createdAt,
        branchName: branches.name,
        branchCode: branches.code,
      })
      .from(employees)
      .innerJoin(branches, eq(employees.branchId, branches.id));

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

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

    const body = await request.json();
    const { employeeId, name, branchId, pin, isAdmin } = body as {
      employeeId?: string;
      name?: string;
      branchId?: string;
      pin?: string;
      isAdmin?: boolean;
    };

    if (!employeeId || !name || !branchId || !pin) {
      return NextResponse.json(
        { success: false, error: 'กรุณาระบุข้อมูลให้ครบถ้วน' },
        { status: 400 }
      );
    }

    // Check employeeId is unique
    const existing = await db
      .select({ id: employees.id })
      .from(employees)
      .where(eq(employees.employeeId, employeeId))
      .limit(1);

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

    const id = generateId();
    const hashedPin = hashPin(pin);

    await db.insert(employees).values({
      id,
      employeeId,
      name,
      branchId,
      pin: hashedPin,
      isAdmin: isAdmin ?? false,
      isActive: true,
      createdAt: new Date(),
    });

    const created = await db
      .select({
        id: employees.id,
        employeeId: employees.employeeId,
        name: employees.name,
        branchId: employees.branchId,
        isAdmin: employees.isAdmin,
        isActive: employees.isActive,
        createdAt: employees.createdAt,
      })
      .from(employees)
      .where(eq(employees.id, id))
      .limit(1);

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

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

    const body = await request.json();
    const { id, name, branchId, pin, isAdmin, isActive } = body as {
      id?: string;
      name?: string;
      branchId?: string;
      pin?: string;
      isAdmin?: boolean;
      isActive?: boolean;
    };

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'กรุณาระบุพนักงานที่ต้องการแก้ไข' },
        { status: 400 }
      );
    }

    // Check employee exists
    const existing = await db
      .select()
      .from(employees)
      .where(eq(employees.id, id))
      .limit(1);

    if (existing.length === 0) {
      return NextResponse.json(
        { success: false, error: 'ไม่พบพนักงานที่ระบุ' },
        { status: 404 }
      );
    }

    // Build update object with only provided fields
    const updateData: Record<string, unknown> = {};
    if (name !== undefined) updateData.name = name;
    if (branchId !== undefined) updateData.branchId = branchId;
    if (pin !== undefined) updateData.pin = hashPin(pin);
    if (isAdmin !== undefined) updateData.isAdmin = isAdmin;
    if (isActive !== undefined) updateData.isActive = isActive;

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { success: false, error: 'ไม่มีข้อมูลที่ต้องการแก้ไข' },
        { status: 400 }
      );
    }

    await db
      .update(employees)
      .set(updateData)
      .where(eq(employees.id, id));

    // Fetch updated employee (without pin)
    const updated = await db
      .select({
        id: employees.id,
        employeeId: employees.employeeId,
        name: employees.name,
        branchId: employees.branchId,
        isAdmin: employees.isAdmin,
        isActive: employees.isActive,
        createdAt: employees.createdAt,
      })
      .from(employees)
      .where(eq(employees.id, id))
      .limit(1);

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

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

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

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'กรุณาระบุพนักงานที่ต้องการลบ' },
        { status: 400 }
      );
    }

    // Check employee exists
    const existing = await db
      .select({ id: employees.id })
      .from(employees)
      .where(eq(employees.id, id))
      .limit(1);

    if (existing.length === 0) {
      return NextResponse.json(
        { success: false, error: 'ไม่พบพนักงานที่ระบุ' },
        { status: 404 }
      );
    }

    // Soft delete: set isActive to false
    await db
      .update(employees)
      .set({ isActive: false })
      .where(eq(employees.id, id));

    return NextResponse.json({
      success: true,
      message: 'ปิดใช้งานพนักงานสำเร็จ',
    });
  } catch (error) {
    console.error('DELETE /api/admin/employees error:', error);
    return NextResponse.json(
      { success: false, error: 'เกิดข้อผิดพลาดในระบบ' },
      { status: 500 }
    );
  }
}
