import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { verifyAffiliateToken } from '../common/affiliate-token';

/**
 * Protects affiliate portal routes. Reads the Bearer token, verifies it, and
 * puts the trusted affiliate id on the request. For `/:id/...` routes it also
 * enforces that the token's affiliate == the id in the URL — so one affiliate
 * can never read or modify another's data.
 */
@Injectable()
export class AffiliateAuthGuard implements CanActivate {
  canActivate(ctx: ExecutionContext): boolean {
    const req = ctx.switchToHttp().getRequest();
    const header = req.headers['authorization'];
    const token = typeof header === 'string' && header.startsWith('Bearer ') ? header.slice(7) : null;

    const claims = verifyAffiliateToken(token);
    if (!claims) throw new UnauthorizedException('Please log in again');

    const paramId = req.params?.id;
    if (paramId && paramId !== claims.id) {
      throw new ForbiddenException('You can only access your own account');
    }

    req.affiliateId = claims.id;
    req.affiliateShop = claims.shop;
    return true;
  }
}
