import { FastifyRequest, FastifyReply } from 'fastify';
import { prisma } from '../../config/database.js';
import { verifyPassword } from '../../utils/crypto.js';
import { errorResponse } from '../../utils/helpers.js';

export async function apiKeyMiddleware(request: FastifyRequest, reply: FastifyReply) {
  const apiKey = request.headers['x-bidcast-api-key'] as string;
  const apiSecret = request.headers['x-bidcast-api-secret'] as string;

  if (!apiKey || !apiSecret) {
    return errorResponse(reply, 'API key and secret required', 401);
  }

  const tenant = await prisma.tenant.findUnique({
    where: { apiKey },
    select: {
      id: true,
      name: true,
      email: true,
      slug: true,
      plan: true,
      isActive: true,
      apiSecretHash: true,
    },
  });

  if (!tenant || !tenant.isActive) {
    return errorResponse(reply, 'Invalid API key or account deactivated', 401);
  }

  const secretValid = await verifyPassword(apiSecret, tenant.apiSecretHash);
  if (!secretValid) {
    return errorResponse(reply, 'Invalid API secret', 401);
  }

  request.tenantId = tenant.id;
  request.tenant = {
    id: tenant.id,
    name: tenant.name,
    email: tenant.email,
    slug: tenant.slug,
    plan: tenant.plan,
    isActive: tenant.isActive,
  };
}
