import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma, UserRole } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { CRM_MODULES, type CrmModule } from './roles.constants';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';

@Injectable()
export class RolesService {
  constructor(private readonly prisma: PrismaService) {}

  // Initializes default Organization Admin role and prunes legacy pre-seeded roles.
  async ensureDefaultRoles(tenantId: string): Promise<void> {
    const existingAdmin = await this.prisma.role.findFirst({
      where: { tenantId, name: 'Organization Admin' },
    });

    let adminRoleId = existingAdmin?.id;

    if (!existingAdmin) {
      adminRoleId = await this.createAdminRole(tenantId);
    } else {
      const existingPerms = await this.prisma.rolePermission.findMany({
        where: { roleId: existingAdmin.id },
      });
      const existingModules = new Set(existingPerms.map((p) => p.module));
      const missingModules = CRM_MODULES.filter((m) => !existingModules.has(m));
      if (missingModules.length > 0) {
        await this.prisma.rolePermission.createMany({
          data: missingModules.map((m) => ({
            roleId: existingAdmin.id,
            module: m,
            canCreate: true,
            canRead: true,
            canUpdate: true,
            canDelete: true,
            canExport: true,
          })),
          skipDuplicates: true,
        });
      }
    }

    if (adminRoleId) {
      await this.prisma.user.updateMany({
        where: { tenantId, role: UserRole.ORGANIZATION_ADMIN, roleId: null },
        data: { roleId: adminRoleId },
      });
    }

    const legacyDescriptions = ['General workspace member with standard read/create access', 'Manage leads, contacts, accounts, deals, and sales activities', 'Manage project delivery, milestones, team hours, and timesheets'];

    const legacyRoles = await this.prisma.role.findMany({
      where: {
        tenantId,
        name: { in: ['Standard Member', 'Sales Representative', 'Project Manager'] },
        description: { in: legacyDescriptions },
        isSystem: false,
      },
    });

    for (const legacy of legacyRoles) {
      await this.prisma.user.updateMany({
        where: { tenantId, roleId: legacy.id },
        data: { roleId: null },
      });
      await this.prisma.rolePermission.deleteMany({
        where: { roleId: legacy.id },
      });
      await this.prisma.role.delete({
        where: { id: legacy.id },
      });
    }
  }

  // Creates the Organization Admin role; when a parallel request created it first, returns that role instead.
  private async createAdminRole(tenantId: string): Promise<string> {
    try {
      const adminRole = await this.prisma.role.create({
        data: {
          tenantId,
          name: 'Organization Admin',
          description: 'Full administrative access across all CRM modules and settings',
          isSystem: true,
          permissions: {
            create: CRM_MODULES.map((m) => ({
              module: m,
              canCreate: true,
              canRead: true,
              canUpdate: true,
              canDelete: true,
              canExport: true,
            })),
          },
        },
      });
      return adminRole.id;
    } catch (err) {
      if (!(err instanceof Prisma.PrismaClientKnownRequestError) || err.code !== 'P2002') throw err;
      const winner = await this.prisma.role.findFirstOrThrow({ where: { tenantId, name: 'Organization Admin' } });
      return winner.id;
    }
  }

  // Returns all roles and permissions within tenant scope.
  async list(tenantId: string) {
    await this.ensureDefaultRoles(tenantId);

    const roles = await this.prisma.role.findMany({
      where: { tenantId },
      include: {
        _count: {
          select: { users: true },
        },
        permissions: {
          orderBy: { module: 'asc' },
        },
      },
      orderBy: [{ isSystem: 'desc' }, { createdAt: 'asc' }],
    });

    return roles.map((r) => ({
      id: r.id,
      name: r.name,
      description: r.description,
      isSystem: r.isSystem,
      userCount: r._count.users,
      permissions: r.permissions,
      createdAt: r.createdAt,
      updatedAt: r.updatedAt,
    }));
  }

  // Retrieves role details and assigned permissions by ID.
  async get(tenantId: string, id: string) {
    await this.ensureDefaultRoles(tenantId);

    const role = await this.prisma.role.findFirst({
      where: { id, tenantId },
      include: {
        _count: {
          select: { users: true },
        },
        permissions: {
          orderBy: { module: 'asc' },
        },
      },
    });

    if (!role) {
      throw new NotFoundException('Role not found');
    }

    return {
      id: role.id,
      name: role.name,
      description: role.description,
      isSystem: role.isSystem,
      userCount: role._count.users,
      permissions: role.permissions,
      createdAt: role.createdAt,
      updatedAt: role.updatedAt,
    };
  }

  // Creates a new custom role with assigned module permissions.
  async create(tenantId: string, dto: CreateRoleDto) {
    await this.ensureDefaultRoles(tenantId);

    const name = dto.name.trim();

    const existing = await this.prisma.role.findFirst({
      where: { tenantId, name },
    });

    if (existing) {
      throw new ConflictException(`A role named "${name}" already exists in this organization`);
    }

    const incomingMap = new Map<string, (typeof dto.permissions)[0]>();
    for (const p of dto.permissions || []) {
      incomingMap.set(p.module, p);
    }

    const permissionCreates = CRM_MODULES.map((m) => {
      const incoming = incomingMap.get(m);
      return {
        module: m,
        canCreate: Boolean(incoming?.canCreate),
        canRead: Boolean(incoming?.canRead),
        canUpdate: Boolean(incoming?.canUpdate),
        canDelete: Boolean(incoming?.canDelete),
        canExport: Boolean(incoming?.canExport),
      };
    });

    const role = await this.prisma.role.create({
      data: {
        tenantId,
        name,
        description: dto.description?.trim() || null,
        isSystem: false,
        permissions: {
          create: permissionCreates,
        },
      },
      include: {
        _count: {
          select: { users: true },
        },
        permissions: {
          orderBy: { module: 'asc' },
        },
      },
    });

    return {
      id: role.id,
      name: role.name,
      description: role.description,
      isSystem: role.isSystem,
      userCount: role._count.users,
      permissions: role.permissions,
      createdAt: role.createdAt,
      updatedAt: role.updatedAt,
    };
  }

  // Updates role name, description, and module permissions.
  async update(tenantId: string, id: string, dto: UpdateRoleDto) {
    const role = await this.prisma.role.findFirst({
      where: { id, tenantId },
    });

    if (!role) {
      throw new NotFoundException('Role not found');
    }

    let nextName = role.name;
    if (dto.name && dto.name.trim() !== role.name) {
      if (role.isSystem) {
        throw new BadRequestException('System role names cannot be renamed');
      }
      nextName = dto.name.trim();
      const nameConflict = await this.prisma.role.findFirst({
        where: { tenantId, name: nextName, NOT: { id } },
      });
      if (nameConflict) {
        throw new ConflictException(`A role named "${nextName}" already exists`);
      }
    }

    await this.prisma.role.update({
      where: { id },
      data: {
        name: nextName,
        description: dto.description !== undefined ? dto.description.trim() || null : undefined,
      },
    });

    if (dto.permissions && dto.permissions.length > 0) {
      for (const p of dto.permissions) {
        if (!CRM_MODULES.includes(p.module as CrmModule)) continue;
        await this.prisma.rolePermission.upsert({
          where: {
            roleId_module: {
              roleId: id,
              module: p.module,
            },
          },
          update: {
            canCreate: p.canCreate,
            canRead: p.canRead,
            canUpdate: p.canUpdate,
            canDelete: p.canDelete,
            canExport: p.canExport,
          },
          create: {
            roleId: id,
            module: p.module,
            canCreate: p.canCreate,
            canRead: p.canRead,
            canUpdate: p.canUpdate,
            canDelete: p.canDelete,
            canExport: p.canExport,
          },
        });
      }
    }

    return this.get(tenantId, id);
  }

  // Deletes a custom role after unlinking assigned members.
  async delete(tenantId: string, id: string) {
    const role = await this.prisma.role.findFirst({
      where: { id, tenantId },
      include: {
        _count: {
          select: { users: true },
        },
      },
    });

    if (!role) {
      throw new NotFoundException('Role not found');
    }

    if (role.isSystem) {
      throw new BadRequestException('System roles cannot be deleted');
    }

    if (role._count.users > 0) {
      throw new ConflictException(`This role is assigned to ${role._count.users} user${role._count.users === 1 ? '' : 's'}. Move them to another role before deleting it.`);
    }

    await this.prisma.rolePermission.deleteMany({
      where: { roleId: id },
    });

    await this.prisma.role.delete({
      where: { id },
    });

    return { success: true, message: `Role "${role.name}" deleted successfully` };
  }
}
