import {
  ConflictException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { AuthService } from '../auth/auth.service.js';
import type { SafeUser } from '../auth/types/auth.types.js';
import { normalizeEmail, normalizeRequiredString } from '../common/utils/normalize.js';
import { PrismaService } from '../prisma/prisma.service.js';
import type { CreateUserDto } from './dto/create-user.dto.js';
import type { ListUsersQueryDto } from './dto/list-users-query.dto.js';
import type { UpdateUserDto } from './dto/update-user.dto.js';
import type { UpdateUserStatusDto } from './dto/update-user-status.dto.js';
import type { PaginatedUsersResponse } from './types/user.types.js';

const SAFE_USER_SELECT = [
  'id',
  'firstName',
  'lastName',
  'email',
  'role',
  'isActive',
  'createdAt',
  'updatedAt',
] as const;

@Injectable()
export class UsersService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly authService: AuthService,
  ) {}

  async create(dto: CreateUserDto): Promise<SafeUser> {
    return this.authService.createUser({
      firstName: dto.firstName,
      lastName: dto.lastName,
      email: dto.email,
      password: dto.password,
      role: dto.role ?? 'SALES_USER',
      isActive: true,
    });
  }

  async findAll(query: ListUsersQueryDto): Promise<PaginatedUsersResponse> {
    return this.listUsers(query, { activeOnly: false });
  }

  async listAssignees(
    query: ListUsersQueryDto,
  ): Promise<PaginatedUsersResponse> {
    return this.listUsers(query, { activeOnly: true });
  }

  async findOne(id: string): Promise<SafeUser> {
    return this.getSafeUserOrThrow(id);
  }

  async update(id: string, dto: UpdateUserDto): Promise<SafeUser> {
    const existing = await this.getSafeUserOrThrow(id);

    const data: {
      firstName?: string;
      lastName?: string;
      email?: string;
      role?: 'ADMIN' | 'SALES_USER';
    } = {};

    if (dto.firstName !== undefined) {
      data.firstName = normalizeRequiredString(dto.firstName);
    }
    if (dto.lastName !== undefined) {
      data.lastName = normalizeRequiredString(dto.lastName);
    }
    if (dto.email !== undefined) {
      data.email = normalizeEmail(dto.email);
      await this.ensureEmailAvailable(data.email, id);
    }
    if (dto.role !== undefined) {
      data.role = dto.role;
      if (existing.role === 'ADMIN' && dto.role !== 'ADMIN') {
        await this.ensureNotLastActiveAdmin(id);
      }
    }

    if (Object.keys(data).length === 0) {
      return existing;
    }

    const updated = await this.prisma.db.orm.public.User.select(
      ...SAFE_USER_SELECT,
    )
      .where((u) => u.id.eq(id))
      .update(data);

    const user = Array.isArray(updated) ? updated[0] : updated;
    if (!user) {
      throw new NotFoundException('User not found');
    }

    return user;
  }

  async updateStatus(
    id: string,
    dto: UpdateUserStatusDto,
  ): Promise<SafeUser> {
    const existing = await this.getSafeUserOrThrow(id);

    if (
      existing.role === 'ADMIN' &&
      existing.isActive &&
      dto.isActive === false
    ) {
      await this.ensureNotLastActiveAdmin(id);
    }

    const updated = await this.prisma.db.orm.public.User.select(
      ...SAFE_USER_SELECT,
    )
      .where((u) => u.id.eq(id))
      .update({ isActive: dto.isActive });

    const user = Array.isArray(updated) ? updated[0] : updated;
    if (!user) {
      throw new NotFoundException('User not found');
    }

    return user;
  }

  private async listUsers(
    query: ListUsersQueryDto,
    options: { activeOnly: boolean },
  ): Promise<PaginatedUsersResponse> {
    const page = query.page ?? 1;
    const limit = query.limit ?? 20;
    const offset = (page - 1) * limit;

    const totalResult = await (
      options.activeOnly
        ? this.prisma.db.orm.public.User.where((u) => u.isActive.eq(true))
        : this.prisma.db.orm.public.User
    ).aggregate((agg) => ({ total: agg.count() }));

    const filtered = options.activeOnly
      ? this.prisma.db.orm.public.User.select(...SAFE_USER_SELECT).where((u) =>
          u.isActive.eq(true),
        )
      : this.prisma.db.orm.public.User.select(...SAFE_USER_SELECT);

    const data = await filtered
      .orderBy((u) => u.createdAt.desc())
      .limit(limit)
      .offset(offset)
      .all();

    const total = totalResult.total;

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages: total === 0 ? 0 : Math.ceil(total / limit),
      },
    };
  }

  private async ensureNotLastActiveAdmin(userId: string): Promise<void> {
    const activeAdmins = await this.prisma.db.orm.public.User.where((u) =>
      u.role.eq('ADMIN'),
    )
      .where((u) => u.isActive.eq(true))
      .aggregate((agg) => ({ total: agg.count() }));

    const target = await this.prisma.db.orm.public.User.select(
      'id',
      'role',
      'isActive',
    )
      .where((u) => u.id.eq(userId))
      .first();

    if (
      target &&
      target.role === 'ADMIN' &&
      target.isActive &&
      activeAdmins.total <= 1
    ) {
      throw new ConflictException(
        'Cannot demote or deactivate the last active admin',
      );
    }
  }

  private async ensureEmailAvailable(
    email: string,
    userId: string,
  ): Promise<void> {
    const existing = await this.prisma.db.orm.public.User.select('id')
      .where((u) => u.email.eq(email))
      .first();

    if (existing && existing.id !== userId) {
      throw new ConflictException('Email is already registered');
    }
  }

  private async getSafeUserOrThrow(id: string): Promise<SafeUser> {
    const user = await this.prisma.db.orm.public.User.select(...SAFE_USER_SELECT)
      .where((u) => u.id.eq(id))
      .first();

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

    return user;
  }
}
