import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import { getDb } from '../db'
import { User } from '../types/context'
import { requireJWTSecret } from '../lib/secret-validation'
import { AppErrors } from '../lib/errors'

// Validate JWT secret at module load time - fails fast if invalid
const JWT_SECRET = requireJWTSecret()
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d'

export interface AuthPayload {
  token: string
  user: User
}

export async function login(email: string, password: string): Promise<AuthPayload> {
  const db = getDb()
  const result = await db.query(
    'SELECT id, email, name, password_hash, role, created_at, updated_at FROM users WHERE email = $1',
    [email]
  )

  if (result.rows.length === 0) {
    throw AppErrors.unauthenticated('Invalid email or password')
  }

  const user = result.rows[0]
  const isValid = await bcrypt.compare(password, user.password_hash)

  if (!isValid) {
    throw AppErrors.unauthenticated('Invalid email or password')
  }

  const token = jwt.sign(
    {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role,
    },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN }
  )

  return {
    token,
    user: {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role,
      createdAt: user.created_at,
      updatedAt: user.updated_at,
    },
  }
}

