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

export async function requireCompanyAuth(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization
  const sessionToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null

  if (!sessionToken) {
    return res.status(401).json({
      error: 'unauthenticated',
      message: 'Authentication required',
      statusCode: 401,
    })
  }

  try {
    const payload = jwt.verify(sessionToken, process.env.JWT_SECRET!) as { sub: string; type: string }
    if (payload.type === 'employee') {
      const employee = await prisma.employee.findUnique({
        where: { id: payload.sub },
        include: { company: true },
      })

      if (!employee || !employee.isActive) {
        return res.status(401).json({
          error: 'unauthenticated',
          message: 'Employee account not found or inactive',
          statusCode: 401,
        })
      }

      req.employee = employee
      req.company = employee.company
      req.companyId = employee.companyId
      return next()
    }
  } catch {
    return res.status(401).json({
      error: 'invalid_token',
      message: 'Invalid or expired session token',
      statusCode: 401,
    })
  }
}
