import { NextResponse } from 'next/server';
import { db } from '@/db/connection';
import { employees, candidates, votes, branches } from '@/db/schema';
import { eq, and } 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/candidates ====================
export async function GET(request: Request) {
  try {
    const authError = checkAdmin(request);
    if (authError) return authError;

    // Get all candidates with employee and branch info
    const candidateList = await db
      .select({
        id: candidates.id,
        employeeId: candidates.employeeId,
        branchId: candidates.branchId,
        position: candidates.position,
        statement: candidates.statement,
        photoUrl: candidates.photoUrl,
        isApproved: candidates.isApproved,
        createdAt: candidates.createdAt,
        name: employees.name,
        employeeCode: employees.employeeId,
        branchName: branches.name,
        branchCode: branches.code,
      })
      .from(candidates)
      .innerJoin(employees, eq(candidates.employeeId, employees.id))
      .innerJoin(branches, eq(candidates.branchId, branches.id));

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

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

    const body = await request.json();
    const { employeeId, branchId, position, statement } = body as {
      employeeId?: string;
      branchId?: string;
      position?: string;
      statement?: string;
    };

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

    // Validate employee exists and belongs to the specified branch
    const employeeResult = await db
      .select({
        id: employees.id,
        name: employees.name,
        branchId: employees.branchId,
      })
      .from(employees)
      .where(eq(employees.id, employeeId))
      .limit(1);

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

    if (employeeResult[0].branchId !== branchId) {
      return NextResponse.json(
        { success: false, error: 'พนักงานไม่ได้อยู่ในสาขาที่ระบุ' },
        { status: 400 }
      );
    }

    // Check if employee is already a candidate
    const existingCandidate = await db
      .select({ id: candidates.id })
      .from(candidates)
      .where(eq(candidates.employeeId, employeeId))
      .limit(1);

    if (existingCandidate.length > 0) {
      return NextResponse.json(
        { success: false, error: 'พนักงานท่านนี้เป็นผู้สมัครอยู่แล้ว' },
        { status: 400 }
      );
    }

    const id = generateId();
    await db.insert(candidates).values({
      id,
      employeeId,
      branchId,
      position: position || null,
      statement: statement || null,
      isApproved: true,
      createdAt: new Date(),
    });

    const created = await db
      .select({
        id: candidates.id,
        employeeId: candidates.employeeId,
        branchId: candidates.branchId,
        position: candidates.position,
        statement: candidates.statement,
        photoUrl: candidates.photoUrl,
        isApproved: candidates.isApproved,
        createdAt: candidates.createdAt,
      })
      .from(candidates)
      .where(eq(candidates.id, id))
      .limit(1);

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

// ==================== DELETE /api/admin/candidates ====================
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 candidate exists
    const candidateResult = await db
      .select({ id: candidates.id })
      .from(candidates)
      .where(eq(candidates.id, id))
      .limit(1);

    if (candidateResult.length === 0) {
      return NextResponse.json(
        { success: false, error: 'ไม่พบผู้สมัครที่ระบุ' },
        { status: 404 }
      );
    }

    // Delete associated votes first
    await db.delete(votes).where(eq(votes.candidateId, id));

    // Delete the candidate
    await db.delete(candidates).where(eq(candidates.id, id));

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