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

    // Total active employees
    const totalEmployeesResult = await db
      .select({ total: count() })
      .from(employees)
      .where(eq(employees.isActive, true));

    const totalEmployees = totalEmployeesResult[0]?.total ?? 0;

    // Total voters (from voteRecords)
    const totalVotersResult = await db
      .select({ total: count() })
      .from(voteRecords);

    const totalVoters = totalVotersResult[0]?.total ?? 0;

    // Total candidates
    const totalCandidatesResult = await db
      .select({ total: count() })
      .from(candidates);

    const totalCandidates = totalCandidatesResult[0]?.total ?? 0;

    // Total votes
    const totalVotesResult = await db
      .select({ total: count() })
      .from(votes);

    const totalVotes = totalVotesResult[0]?.total ?? 0;

    // Overall participation rate
    const overallParticipation =
      totalEmployees > 0
        ? Math.round((totalVoters / totalEmployees) * 10000) / 100
        : 0;

    // Votes by branch
    // Get vote counts per branch
    const votesByBranchResult = await db
      .select({
        branchId: votes.branchId,
        branchName: branches.name,
        branchCode: branches.code,
        totalVotes: count(),
      })
      .from(votes)
      .innerJoin(branches, eq(votes.branchId, branches.id))
      .groupBy(votes.branchId, branches.name, branches.code);

    // Get eligible voters per branch (active employees)
    const eligibleByBranchResult = await db
      .select({
        branchId: employees.branchId,
        totalEligibleVoters: count(),
      })
      .from(employees)
      .where(eq(employees.isActive, true))
      .groupBy(employees.branchId);

    // Get voter count per branch (employees who have voted)
    const votersByBranchResult = await db
      .select({
        branchId: employees.branchId,
        totalVoters: count(),
      })
      .from(voteRecords)
      .innerJoin(employees, eq(voteRecords.employeeId, employees.id))
      .groupBy(employees.branchId);

    // Build lookup maps
    const eligibleMap = new Map<string, number>();
    for (const row of eligibleByBranchResult) {
      eligibleMap.set(row.branchId, row.totalEligibleVoters);
    }

    const votersMap = new Map<string, number>();
    for (const row of votersByBranchResult) {
      votersMap.set(row.branchId, row.totalVoters);
    }

    // Build votes by branch array, including branches with no votes
    const allBranches = await db.select().from(branches);

    const votesByBranch = allBranches.map((branch) => {
      const voteData = votesByBranchResult.find(
        (v) => v.branchId === branch.id
      );
      const totalEligible = eligibleMap.get(branch.id) ?? 0;
      const branchVoters = votersMap.get(branch.id) ?? 0;
      const branchVotes = voteData?.totalVotes ?? 0;
      const participationRate =
        totalEligible > 0
          ? Math.round((branchVoters / totalEligible) * 10000) / 100
          : 0;

      return {
        branchId: branch.id,
        branchName: branch.name,
        branchCode: branch.code,
        totalVotes: branchVotes,
        totalEligibleVoters: totalEligible,
        totalVoters: branchVoters,
        participationRate,
      };
    });

    // Sort by branch code
    votesByBranch.sort((a, b) => a.branchCode.localeCompare(b.branchCode));

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