import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
import { AuthService } from '../auth.service';
import { PrismaService } from '../../prisma/prisma.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  private readonly logger = new Logger(LocalStrategy.name);

  constructor(
    private authService: AuthService,
    private prisma: PrismaService,
  ) {
    super({
      usernameField: 'username',
      passwordField: 'password',
      passReqToCallback: true, // 允许访问request对象
    });
  }

  async validate(req: any, username: string, password: string): Promise<any> {
    // 从请求体或请求头获取租户信息
    const tenantCode = req.body?.tenantCode || req.headers['x-tenant-code'];
    const tenantId = req.headers['x-tenant-id'];

    this.logger.debug(`Login attempt: username=${username}, tenantCode=${tenantCode}, tenantId=${tenantId}`);

    let finalTenantId: number | undefined;

    if (tenantId) {
      finalTenantId = parseInt(tenantId, 10);
    } else if (tenantCode) {
      const tenant = await this.prisma.tenant.findUnique({
        where: { code: tenantCode },
      });
      this.logger.debug(`Tenant lookup result: ${JSON.stringify(tenant)}`);
      if (!tenant) {
        throw new UnauthorizedException('租户不存在');
      }
      finalTenantId = tenant.id;
    }

    const user = await this.authService.validateUser(username, password, finalTenantId);
    if (!user) {
      throw new UnauthorizedException('用户名或密码错误');
    }
    return user;
  }
}
