import { NextResponse } from 'next/server';
import { db } from '@/db/connection';
import { employees, branches } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { hashPin, createSessionToken, setSessionCookie, type AuthUser } from '@/lib/auth';

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { employeeId, pin } = body;

    if (!employeeId || !pin) {
      return NextResponse.json(
        { success: false, error: 'กรุณาระบุรหัสพนักงานและ PIN' },
        { status: 400 }
      );
    }

    // Look up employee by employeeId, joining branches to get branch name
    const result = await db
      .select({
        id: employees.id,
        employeeId: employees.employeeId,
        name: employees.name,
        branchId: employees.branchId,
        isAdmin: employees.isAdmin,
        pin: employees.pin,
        isActive: employees.isActive,
        branchName: branches.name,
      })
      .from(employees)
      .leftJoin(branches, eq(employees.branchId, branches.id))
      .where(eq(employees.employeeId, employeeId));

    const employee = result[0];

    if (!employee) {
      return NextResponse.json(
        { success: false, error: 'รหัสพนักงานหรือ PIN ไม่ถูกต้อง' },
        { status: 401 }
      );
    }

    // Check if employee is active
    if (!employee.isActive) {
      return NextResponse.json(
        { success: false, error: 'บัญชีพนักงานนี้ถูกปิดใช้งาน' },
        { status: 403 }
      );
    }

    // Verify PIN
    const hashedPin = hashPin(pin);
    if (hashedPin !== employee.pin) {
      return NextResponse.json(
        { success: false, error: 'รหัสพนักงานหรือ PIN ไม่ถูกต้อง' },
        { status: 401 }
      );
    }

    // Create session
    const authUser: AuthUser = {
      employeeId: employee.employeeId,
      name: employee.name,
      branchId: employee.branchId,
      branchName: employee.branchName ?? '',
      isAdmin: employee.isAdmin,
      dbId: employee.id,
    };

    const token = createSessionToken(authUser);
    const cookieHeader = setSessionCookie(token);

    const response = NextResponse.json({
      success: true,
      user: {
        employeeId: authUser.employeeId,
        name: authUser.name,
        branchId: authUser.branchId,
        branchName: authUser.branchName,
        isAdmin: authUser.isAdmin,
        dbId: authUser.dbId,
      },
    });

    response.headers.set('Set-Cookie', cookieHeader);

    return response;
  } catch (error) {
    console.error('Login error:', error);
    return NextResponse.json(
      { success: false, error: 'เกิดข้อผิดพลาดในระบบ' },
      { status: 500 }
    );
  }
}
