/**
 * Auth Middleware - Token validation
 */

import type { Context, Next } from 'hono';
import { pocketbaseService } from '../services/pocketbaseService';
import { HTTP_STATUS, ERROR_MESSAGES } from '../config/constants';

/**
 * Validate auth token and attach user to context
 */
export async function authMiddleware(c: Context, next: Next): Promise<Response | void> {
  const authHeader = c.req.header('Authorization');

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return c.json(
      { error: ERROR_MESSAGES.UNAUTHORIZED },
      HTTP_STATUS.UNAUTHORIZED
    );
  }

  const token = authHeader.slice(7); // Remove 'Bearer '

  try {
    // Validate token with PocketBase
    const user = await pocketbaseService.authenticateWithToken(token);

    if (!user) {
      return c.json(
        { error: ERROR_MESSAGES.TOKEN_INVALID },
        HTTP_STATUS.UNAUTHORIZED
      );
    }

    // Attach user info to context
    c.set('userId', user.id);
    c.set('user', user);
    c.set('token', token);

    await next();
  } catch (err) {
    console.error('[AuthMiddleware] Token validation failed:', err);
    return c.json(
      { error: ERROR_MESSAGES.TOKEN_INVALID },
      HTTP_STATUS.UNAUTHORIZED
    );
  }
}

/**
 * Optional auth - doesn't fail if no token, but attaches user if present
 */
export async function optionalAuthMiddleware(c: Context, next: Next): Promise<Response | void> {
  const authHeader = c.req.header('Authorization');

  if (authHeader && authHeader.startsWith('Bearer ')) {
    const token = authHeader.slice(7);

    try {
      const user = await pocketbaseService.authenticateWithToken(token);
      if (user) {
        c.set('userId', user.id);
        c.set('user', user);
        c.set('token', token);
      }
    } catch {
      // Silently continue without auth
    }
  }

  await next();
}

/**
 * Get user ID from context (for use after auth middleware)
 */
export function getUserId(c: Context): string {
  const userId = c.get('userId');
  if (!userId) {
    throw new Error('User ID not found in context - auth middleware not applied?');
  }
  return userId as string;
}

/**
 * Get user from context
 */
export function getUser(c: Context): unknown {
  return c.get('user');
}
