import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { envs } from 'src/config';
import { PrismaService } from 'src/prisma/prisma.service';

export interface StoreJwtPayload {
  sub: string;       // ecommerce_clientes.id
  empresa_id: string;
  scope: 'store_customer';
}

@Injectable()
export class StoreJwtStrategy extends PassportStrategy(Strategy, 'store-jwt') {
  constructor(private readonly prisma: PrismaService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: envs.jwtSecret,
    });
  }

  async validate(payload: StoreJwtPayload) {
    if (payload.scope !== 'store_customer') throw new UnauthorizedException('Token inválido');
    const cliente = await this.prisma.ecommerce_clientes.findUnique({
      where: { id: payload.sub },
      select: { id: true, empresa_id: true, email: true, nombre: true, telefono: true, documento: true, activo: true },
    });
    if (!cliente || !cliente.activo) throw new UnauthorizedException('Cliente no autorizado');
    return cliente;
  }
}
