import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import type { AuthUser } from '../trpc/auth-user';
import { verifyPassword } from './password';

const userInclude = {
  roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } },
} satisfies Prisma.UserInclude;

type UserWithRoles = Prisma.UserGetPayload<{ include: typeof userInclude }>;

@Injectable()
export class AuthService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly jwt: JwtService,
    private readonly config: ConfigService,
  ) {}

  /** The refresh token is signed with its own secret and carries a marker, so an
   *  access token can never be replayed as a refresh token or the other way
   *  round — the two secrets are already required to differ by config/env.ts. */
  private signRefresh(userId: string): Promise<string> {
    return this.jwt.signAsync(
      { sub: userId, typ: 'refresh' },
      {
        secret: this.config.get<string>('JWT_REFRESH_SECRET'),
        expiresIn: (this.config.get<string>('JWT_REFRESH_TTL') ?? '30d') as `${number}d`,
      },
    );
  }

  async login(email: string, password: string): Promise<{ accessToken: string; refreshToken: string; user: AuthUser }> {
    const user = await this.prisma.user.findUnique({ where: { email }, include: userInclude });
    if (!user || !user.isActive || !verifyPassword(password, user.passwordHash)) {
      throw new UnauthorizedException('Invalid email or password');
    }
    const accessToken = await this.jwt.signAsync({ sub: user.id });
    return { accessToken, refreshToken: await this.signRefresh(user.id), user: this.toAuthUser(user) };
  }

  /** Exchange a refresh token for a new access token. The access TTL is 15
   *  minutes, which without this means every session dies mid-form four times
   *  an hour. The user is re-read so a deactivated account, or one whose roles
   *  changed, stops working at the next refresh rather than at the next login.
   *  A new refresh token is issued too, so the window slides: a session that
   *  keeps being used keeps moving its own deadline. Note this is re-issue, not
   *  rotation in the security sense — the previous refresh token stays valid
   *  until it expires, since nothing here tracks or revokes issued tokens. */
  async refresh(refreshToken: string): Promise<{ accessToken: string; refreshToken: string; user: AuthUser }> {
    let payload: { sub: string; typ?: string };
    try {
      payload = await this.jwt.verifyAsync<{ sub: string; typ?: string }>(refreshToken, {
        secret: this.config.get<string>('JWT_REFRESH_SECRET'),
      });
    } catch {
      throw new UnauthorizedException('Session expired, please sign in again');
    }
    if (payload.typ !== 'refresh') throw new UnauthorizedException('Session expired, please sign in again');
    const user = await this.prisma.user.findUnique({ where: { id: payload.sub }, include: userInclude });
    if (!user || !user.isActive) throw new UnauthorizedException('Session expired, please sign in again');
    return {
      accessToken: await this.jwt.signAsync({ sub: user.id }),
      refreshToken: await this.signRefresh(user.id),
      user: this.toAuthUser(user),
    };
  }

  async verifyAndLoad(token: string): Promise<AuthUser | null> {
    try {
      const payload = await this.jwt.verifyAsync<{ sub: string }>(token);
      const user = await this.prisma.user.findUnique({ where: { id: payload.sub }, include: userInclude });
      if (!user || !user.isActive) return null;
      return this.toAuthUser(user);
    } catch {
      return null;
    }
  }

  private toAuthUser(user: UserWithRoles): AuthUser {
    const roles = user.roles.map((r) => r.role.code);
    const permissions = [
      ...new Set(user.roles.flatMap((r) => r.role.permissions.map((p) => p.permission.key))),
    ];
    return {
      id: user.id,
      email: user.email,
      name: user.name,
      tenantId: user.tenantId,
      mustChangePassword: user.mustChangePassword,
      roles,
      permissions,
    };
  }
}
