import { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import { prisma } from '../lib/prisma'
import { getCookie, sendUnauthorized } from './authHelpers'

/**
 * Validates a company-scoped Bearer token and loads the employee + company onto `req`.
 *
 * Guarantees on success:
 *   req.employee  — full employee record (with company relation)
 *   req.company   — the employee's company
 *   req.companyId — string shorthand for req.company.id
 */
async function authenticateCompanyRequest(req: Request, res: Response, next: NextFunction, allowCookie = false) {
  const authHeader = req.headers.authorization
  const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null
  const cookieToken = allowCookie ? getCookie(req, 'employee_token') : null
  const token = bearerToken ?? cookieToken

  if (!token) return sendUnauthorized(res, 'unauthenticated', 'Authentication required')

  let payload: { sub: string; type: string }
  try {
    payload = jwt.verify(token, process.env.JWT_SECRET!) as { sub: string; type: string }
  } catch {
    return sendUnauthorized(res, 'invalid_token', 'Invalid or expired session token')
  }

  if (payload.type !== 'employee') {
    return sendUnauthorized(res, 'invalid_token', 'Invalid token type for this endpoint')
  }

  const employee = await prisma.employee.findUnique({
    where: { id: payload.sub },
    include: { company: true },
  })

  if (!employee || !employee.isActive) {
    return sendUnauthorized(res, 'unauthenticated', 'Employee account not found or inactive')
  }

  req.employee  = employee
  req.company   = employee.company
  req.companyId = employee.companyId
  next()
}

export async function requireCompanyAuth(req: Request, res: Response, next: NextFunction) {
  return authenticateCompanyRequest(req, res, next)
}

export async function requireCompanyDocumentAuth(req: Request, res: Response, next: NextFunction) {
  return authenticateCompanyRequest(req, res, next, true)
}
