import { Injectable, UnauthorizedException, BadRequestException, NotFoundException, ServiceUnavailableException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../../prisma/prisma.service';
import { EmailService } from '../email/email.service';
import { LoginDto } from './dto/login.dto';
import { ForgotPasswordDto } from './dto/forgot-password.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { AcceptInviteDto } from './dto/accept-invite.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { RequestResetLinkDto } from './dto/request-reset-link.dto';
import { JwtPayload } from '../../common/auth/jwt-payload.interface';
import { getJwtSecret } from '../../common/auth/jwt-secret';
import { OrganizationStatus, Prisma, UserRole, UserStatus } from '@prisma/client';
import * as bcrypt from 'bcryptjs';
import * as crypto from 'crypto';
import { resolvePrimaryWebOrigin } from '../../common/utils/web-origin';

const MAX_FAILED_LOGINS = 5;
const LOCKOUT_MS = 15 * 60 * 1000;
const RESET_TOKEN_TTL_MS = 60 * 60 * 1000;
/** Minimum gap between two reset emails to the same account (stops email flooding). */
const RESET_EMAIL_COOLDOWN_MS = 60 * 1000;
const INVALID_CREDENTIALS = 'Invalid email or password';
const FORGOT_PASSWORD_REPLY = 'If that email address exists in our system, a password reset link has been sent.';

// Compared against when the email is unknown, so response time does not reveal
// whether an account exists.
const DUMMY_PASSWORD_HASH = bcrypt.hashSync(crypto.randomBytes(16).toString('hex'), 10);

type UserWithOrg = Prisma.UserGetPayload<{
  include: {
    organization: true;
    customRole: {
      include: {
        permissions: true;
      };
    };
  };
}>;

@Injectable()
export class AuthService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly jwtService: JwtService,
    private readonly emailService: EmailService,
  ) {}

  // Signs a JWT session token for an authenticated user.
  async revokeSession(token: string): Promise<void> {
    try {
      const payload = await this.jwtService.verifyAsync<JwtPayload>(token, {
        secret: getJwtSecret(),
      });
      if (payload?.sub) {
        await this.prisma.user.update({
          where: { id: payload.sub },
          data: { sessionVersion: { increment: 1 } },
        });
      }
    } catch {
      // If token is invalid or expired, session is already invalid
    }
  }
  private signSession(user: UserWithOrg): Promise<string> {
    const payload: JwtPayload = {
      sub: user.id,
      email: user.email,
      role: user.role,
      tenantId: user.tenantId,
      name: user.name,
      sv: user.sessionVersion,
    };
    return this.jwtService.signAsync(payload, {
      secret: getJwtSecret(),
      expiresIn: '7d',
    });
  }

  // Sanitizes database user record into session user payload.
  private toSessionUser(user: UserWithOrg) {
    return {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
      roleId: user.roleId,
      customRole: user.customRole
        ? {
            id: user.customRole.id,
            name: user.customRole.name,
            isSystem: user.customRole.isSystem,
            permissions: user.customRole.permissions,
          }
        : null,
      tenantId: user.tenantId,
      canDelete: user.canDelete,
      canExport: user.canExport,
      organization: user.organization
        ? {
            id: user.organization.id,
            name: user.organization.name,
            status: user.organization.status,
            logoFileId: user.organization.logoFileId,
          }
        : null,
    };
  }

  // Authenticates user credentials with rate limiting and lockout protection.
  async login(dto: LoginDto, _ipAddress?: string) {
    const user = await this.prisma.user.findUnique({
      where: { email: dto.email.toLowerCase().trim() },
      include: {
        organization: true,
        customRole: {
          include: {
            permissions: true,
          },
        },
      },
    });

    if (!user) {
      await bcrypt.compare(dto.password, DUMMY_PASSWORD_HASH);
      throw new UnauthorizedException(INVALID_CREDENTIALS);
    }

    const now = Date.now();
    if (user.lockedUntil && user.lockedUntil.getTime() > now) {
      const remainingMinutes = Math.ceil((user.lockedUntil.getTime() - now) / (60 * 1000));
      throw new UnauthorizedException(`Account is locked due to multiple failed sign-in attempts. Try again in ${remainingMinutes} minute(s) or reset your password.`);
    }

    const lockExpired = !!user.lockedUntil;
    const isPasswordValid = await bcrypt.compare(dto.password, user.passwordHash ?? DUMMY_PASSWORD_HASH);

    if (!isPasswordValid || !user.passwordHash) {
      const updated = await this.prisma.user.update({
        where: { id: user.id },
        data: lockExpired ? { failedLoginAttempts: 1, lockedUntil: null } : { failedLoginAttempts: { increment: 1 } },
        select: { failedLoginAttempts: true },
      });

      if (updated.failedLoginAttempts >= MAX_FAILED_LOGINS) {
        await this.prisma.user.update({
          where: { id: user.id },
          data: { lockedUntil: new Date(now + LOCKOUT_MS) },
        });
        throw new UnauthorizedException('Account is locked for 15 minutes after 5 failed sign-in attempts.');
      }

      throw new UnauthorizedException(INVALID_CREDENTIALS);
    }

    if (user.status !== UserStatus.ACTIVE) {
      throw new UnauthorizedException('Account is not active. Please contact your administrator.');
    }

    if (user.organization?.status === OrganizationStatus.SUSPENDED) {
      throw new UnauthorizedException('Organization access has been suspended. Please contact platform support.');
    }

    const signedIn = await this.prisma.user.update({
      where: { id: user.id },
      data: {
        failedLoginAttempts: 0,
        lockedUntil: null,
        lastLoginAt: new Date(),
      },
      include: {
        organization: true,
        customRole: {
          include: {
            permissions: true,
          },
        },
      },
    });

    return {
      accessToken: await this.signSession(signedIn),
      user: this.toSessionUser(signedIn),
    };
  }

  // Returns the profile and permissions for the currently authenticated user.
  async getMe(userId: string) {
    let user = await this.prisma.user.findUnique({
      where: { id: userId },
      include: {
        organization: true,
        customRole: {
          include: {
            permissions: true,
          },
        },
      },
    });

    if (!user) {
      throw new NotFoundException('User not found');
    }

    if (user.tenantId && !user.customRole && user.role === UserRole.ORGANIZATION_ADMIN) {
      const defaultRole = await this.prisma.role.findFirst({
        where: {
          tenantId: user.tenantId,
          name: 'Organization Admin',
        },
      });
      if (defaultRole) {
        await this.prisma.user.update({
          where: { id: userId },
          data: { roleId: defaultRole.id },
        });
        user = await this.prisma.user.findUnique({
          where: { id: userId },
          include: {
            organization: true,
            customRole: {
              include: {
                permissions: true,
              },
            },
          },
        });
        if (!user) {
          throw new NotFoundException('User not found');
        }
      }
    }

    return {
      ...this.toSessionUser(user),
      status: user.status,
      lastLoginAt: user.lastLoginAt,
    };
  }

  // Updates current user profile details such as display name.
  async updateProfile(userId: string, dto: UpdateProfileDto) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
    });
    if (!user) {
      throw new NotFoundException('User not found');
    }

    const updated = await this.prisma.user.update({
      where: { id: userId },
      data: {
        name: dto.name.trim(),
      },
      include: {
        organization: true,
        customRole: {
          include: {
            permissions: true,
          },
        },
      },
    });

    return {
      ...this.toSessionUser(updated),
      status: updated.status,
      lastLoginAt: updated.lastLoginAt,
    };
  }

  // Changes password for currently authenticated user after verifying current password.
  async changePassword(userId: string, dto: ChangePasswordDto) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
    });
    if (!user) {
      throw new NotFoundException('User not found');
    }

    if (!user.passwordHash) {
      throw new BadRequestException('Current password is incorrect');
    }

    const validCurrent = await bcrypt.compare(dto.currentPassword, user.passwordHash);
    if (!validCurrent) {
      throw new BadRequestException('Current password is incorrect');
    }

    if (dto.currentPassword === dto.newPassword) {
      throw new BadRequestException('New password must be different from current password');
    }

    const passwordHash = await bcrypt.hash(dto.newPassword, 10);
    await this.prisma.user.update({
      where: { id: userId },
      data: {
        passwordHash,
        sessionVersion: { increment: 1 },
      },
    });

    return {
      success: true,
      message: 'Password changed successfully',
    };
  }

  // Verifies current password and emails a reset link to the authenticated user's address.
  async sendResetLinkWithPassword(userId: string, dto: RequestResetLinkDto) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
    });
    if (!user) {
      throw new NotFoundException('User not found');
    }

    if (!user.passwordHash) {
      throw new BadRequestException('Current password is incorrect');
    }

    const validCurrent = await bcrypt.compare(dto.currentPassword, user.passwordHash);
    if (!validCurrent) {
      throw new BadRequestException('Current password is incorrect');
    }

    const rawToken = crypto.randomBytes(32).toString('hex');
    const resetTokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');

    await this.prisma.user.update({
      where: { id: user.id },
      data: {
        resetTokenHash,
        resetTokenExpiresAt: new Date(Date.now() + RESET_TOKEN_TTL_MS),
      },
    });

    const resetLink = `${resolvePrimaryWebOrigin()}/reset-password?token=${rawToken}`;
    const sent = await this.emailService.sendPasswordResetEmail(user.email, resetLink);
    const delivered = sent.success || (sent.mocked && process.env.NODE_ENV !== 'production');
    if (!delivered) {
      throw new ServiceUnavailableException('The email could not be sent. Check the email settings or try again later.');
    }

    return {
      success: true,
      message: 'Password reset link sent to your registered email address.',
    };
  }

  // Generates and emails a password reset link if the user exists.
  async forgotPassword(dto: ForgotPasswordDto) {
    const user = await this.prisma.user.findUnique({
      where: { email: dto.email.toLowerCase().trim() },
    });

    if (!user || user.status !== UserStatus.ACTIVE) {
      return { message: FORGOT_PASSWORD_REPLY };
    }

    if (user.resetTokenExpiresAt && user.resetTokenExpiresAt.getTime() - RESET_TOKEN_TTL_MS > Date.now() - RESET_EMAIL_COOLDOWN_MS) {
      return { message: FORGOT_PASSWORD_REPLY };
    }

    const rawToken = crypto.randomBytes(32).toString('hex');
    const resetTokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');

    await this.prisma.user.update({
      where: { id: user.id },
      data: {
        resetTokenHash,
        resetTokenExpiresAt: new Date(Date.now() + RESET_TOKEN_TTL_MS),
      },
    });

    const resetLink = `${resolvePrimaryWebOrigin()}/reset-password?token=${rawToken}`;
    await this.emailService.sendPasswordResetEmail(user.email, resetLink);

    return { message: FORGOT_PASSWORD_REPLY };
  }

  // Resets a user's password using a valid reset token and increments session version.
  async resetPassword(dto: ResetPasswordDto) {
    const hashedToken = crypto.createHash('sha256').update(dto.token).digest('hex');

    const user = await this.prisma.user.findFirst({
      where: {
        resetTokenHash: hashedToken,
        resetTokenExpiresAt: { gt: new Date() },
      },
    });

    if (!user) {
      throw new BadRequestException('Invalid or expired password reset link');
    }

    const newPasswordHash = await bcrypt.hash(dto.newPassword, 10);

    const result = await this.prisma.user.updateMany({
      where: { id: user.id, resetTokenHash: hashedToken },
      data: {
        passwordHash: newPasswordHash,
        resetTokenHash: null,
        resetTokenExpiresAt: null,
        failedLoginAttempts: 0,
        lockedUntil: null,
        sessionVersion: { increment: 1 },
      },
    });

    if (result.count === 0) {
      throw new BadRequestException('Invalid or expired password reset link');
    }

    return {
      message: 'Your password has been successfully reset. You can now sign in.',
    };
  }

  // Retrieves invitation metadata for pre-filling accept invite page.
  async getInviteInfo(rawToken: string) {
    if (!rawToken || !rawToken.trim()) {
      throw new BadRequestException('Invitation token is required');
    }
    const hashedToken = crypto.createHash('sha256').update(rawToken.trim()).digest('hex');

    const user = await this.prisma.user.findFirst({
      where: {
        invitationTokenHash: hashedToken,
        invitationTokenExpiresAt: { gt: new Date() },
        status: UserStatus.INVITED,
      },
      include: {
        organization: {
          select: {
            name: true,
            city: true,
          },
        },
      },
    });

    if (!user) {
      throw new BadRequestException('Invalid or expired invitation link');
    }

    return {
      name: user.name,
      email: user.email,
      organizationName: user.organization?.name || 'TechCMantix Workspace',
    };
  }

  // Accepts an organization invitation and initializes user credentials.
  async acceptInvite(dto: AcceptInviteDto) {
    const hashedToken = crypto.createHash('sha256').update(dto.token).digest('hex');

    const user = await this.prisma.user.findFirst({
      where: {
        invitationTokenHash: hashedToken,
        invitationTokenExpiresAt: { gt: new Date() },
        status: UserStatus.INVITED,
      },
      include: { organization: true },
    });

    if (!user) {
      throw new BadRequestException('Invalid or expired invitation link');
    }

    if (user.organization?.status === OrganizationStatus.SUSPENDED) {
      throw new BadRequestException('This organization is suspended. Please contact platform support.');
    }

    const passwordHash = await bcrypt.hash(dto.password, 10);

    const result = await this.prisma.user.updateMany({
      where: { id: user.id, invitationTokenHash: hashedToken },
      data: {
        name: dto.name.trim(),
        passwordHash,
        status: UserStatus.ACTIVE,
        invitationTokenHash: null,
        invitationTokenExpiresAt: null,
        sessionVersion: { increment: 1 },
        lastLoginAt: new Date(),
      },
    });

    if (result.count === 0) {
      throw new BadRequestException('Invalid or expired invitation link');
    }

    const activated = await this.prisma.user.findUniqueOrThrow({
      where: { id: user.id },
      include: {
        organization: true,
        customRole: {
          include: {
            permissions: true,
          },
        },
      },
    });

    return {
      accessToken: await this.signSession(activated),
      user: this.toSessionUser(activated),
    };
  }
}
