import { Injectable, NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { EmailService } from '../email/email.service';
import { UpdateOrganizationDto } from './dto/update-organization.dto';
import { InviteMemberDto } from './dto/invite-member.dto';
import { UpdateMemberPermissionsDto } from './dto/update-member-permissions.dto';
import { UpdateMemberStatusDto } from './dto/update-member-status.dto';
import { UpdateMemberRoleDto } from './dto/update-member-role.dto';
import { RolesService } from '../roles/roles.service';
import { UserRole, UserStatus } from '@prisma/client';
import * as crypto from 'crypto';
import { resolvePrimaryWebOrigin } from '../../common/utils/web-origin';
import { inviteDeliveryResult } from '../../common/utils/invite-response';

import { isValidGstin, deriveStateCodeFromGstin } from '../../common/utils/gstin-validator';

@Injectable()
export class OrganizationService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly emailService: EmailService,
    private readonly rolesService: RolesService,
  ) {}

  // Retrieves organization details and record counts by tenant ID.
  async getOrganization(tenantId: string) {
    const org = await this.prisma.organization.findUnique({
      where: { id: tenantId },
      include: {
        _count: {
          select: {
            users: true,
            leads: true,
            contacts: true,
            customers: true,
            deals: true,
          },
        },
      },
    });

    if (!org) {
      throw new NotFoundException('Organization not found');
    }

    return {
      ...org,
      _count: {
        ...org._count,
        accounts: org._count.customers,
      },
    };
  }

  // Updates organization metadata such as company name and billing profile.
  async updateOrganization(tenantId: string, dto: UpdateOrganizationDto) {
    const org = await this.prisma.organization.findUnique({
      where: { id: tenantId },
    });

    if (!org) {
      throw new NotFoundException('Organization not found');
    }

    let gstin = dto.gstin?.trim()?.toUpperCase();
    let stateCode = dto.stateCode?.trim();

    if (gstin) {
      if (!isValidGstin(gstin)) {
        throw new BadRequestException('Invalid GSTIN format. Expected 15-character Indian GSTIN');
      }
      if (!stateCode) {
        stateCode = deriveStateCodeFromGstin(gstin) || undefined;
      }
    }

    const pan = dto.pan?.trim().toUpperCase();
    if (pan && !/^[A-Z]{5}[0-9]{4}[A-Z]$/.test(pan)) {
      throw new BadRequestException('Invalid PAN format. Expected 10 characters: 5 letters, 4 digits, 1 letter');
    }
    const ifsc = dto.bankIfsc?.trim().toUpperCase();
    if (ifsc && !/^[A-Z]{4}0[A-Z0-9]{6}$/.test(ifsc)) {
      throw new BadRequestException('Invalid IFSC format. Expected 11 characters: 4 letters, a zero, then 6 letters or digits');
    }
    for (const fileId of [dto.logoFileId, dto.signatureFileId]) {
      if (fileId && !(await this.prisma.file.findFirst({ where: { id: fileId, tenantId }, select: { id: true } }))) {
        throw new BadRequestException('The selected image was not found in this organization');
      }
    }

    return this.prisma.organization.update({
      where: { id: tenantId },
      data: {
        name: dto.name ? dto.name.trim() : undefined,
        phone: dto.phone !== undefined ? dto.phone?.trim() || null : undefined,
        legalName: dto.legalName !== undefined ? dto.legalName?.trim() : undefined,
        gstin: gstin !== undefined ? gstin : undefined,
        stateCode: stateCode !== undefined ? stateCode : undefined,
        pan: dto.pan !== undefined ? dto.pan?.trim()?.toUpperCase() : undefined,
        addressLine1: dto.addressLine1 !== undefined ? dto.addressLine1?.trim() : undefined,
        addressLine2: dto.addressLine2 !== undefined ? dto.addressLine2?.trim() : undefined,
        city: dto.city !== undefined ? dto.city?.trim() : undefined,
        postalCode: dto.postalCode !== undefined ? dto.postalCode?.trim() : undefined,
        country: dto.country !== undefined ? dto.country?.trim() : undefined,
        bankName: dto.bankName !== undefined ? dto.bankName?.trim() : undefined,
        bankAccountNumber: dto.bankAccountNumber !== undefined ? dto.bankAccountNumber?.trim() : undefined,
        bankIfsc: dto.bankIfsc !== undefined ? dto.bankIfsc?.trim()?.toUpperCase() : undefined,
        bankBranch: dto.bankBranch !== undefined ? dto.bankBranch?.trim() : undefined,
        defaultTerms: dto.defaultTerms !== undefined ? dto.defaultTerms : undefined,
        logoFileId: dto.logoFileId !== undefined ? dto.logoFileId : undefined,
        signatureFileId: dto.signatureFileId !== undefined ? dto.signatureFileId : undefined,
      },
    });
  }

  // Returns active workspace members for user directory selectors.
  async directory(tenantId: string) {
    return this.prisma.user.findMany({
      where: { tenantId, status: UserStatus.ACTIVE },
      select: { id: true, name: true, role: true },
      orderBy: { name: 'asc' },
    });
  }

  // Lists all user profiles and roles in the organization.
  async listUsers(tenantId: string) {
    await this.rolesService.ensureDefaultRoles(tenantId);

    return this.prisma.user.findMany({
      where: { tenantId },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        roleId: true,
        customRole: {
          select: {
            id: true,
            name: true,
            isSystem: true,
            permissions: true,
          },
        },
        status: true,
        canDelete: true,
        canExport: true,
        lastLoginAt: true,
        createdAt: true,
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  // Retrieves user profile by ID within organization scope.
  async getUser(tenantId: string, userId: string) {
    await this.rolesService.ensureDefaultRoles(tenantId);

    const user = await this.prisma.user.findFirst({
      where: { id: userId, tenantId },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        roleId: true,
        customRole: {
          select: {
            id: true,
            name: true,
            isSystem: true,
            permissions: true,
          },
        },
        status: true,
        canDelete: true,
        canExport: true,
        lastLoginAt: true,
        createdAt: true,
      },
    });

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

    return user;
  }

  // Invites a new team member and delivers invitation link via email.
  async inviteMember(tenantId: string, dto: InviteMemberDto) {
    await this.rolesService.ensureDefaultRoles(tenantId);

    const org = await this.prisma.organization.findUnique({
      where: { id: tenantId },
    });

    if (!org) {
      throw new NotFoundException('Organization not found');
    }

    const email = dto.email.toLowerCase().trim();

    const existingUser = await this.prisma.user.findUnique({
      where: { email },
    });

    if (existingUser) {
      throw new ConflictException(`A user with email "${email}" already exists`);
    }

    let roleId: string | undefined = undefined;
    let baseRole: UserRole = UserRole.ORGANIZATION_MEMBER;
    if (dto.roleId) {
      const assignedRole = await this.prisma.role.findFirst({
        where: { id: dto.roleId, tenantId },
      });
      if (!assignedRole) {
        throw new NotFoundException('Selected role does not exist in this organization');
      }
      roleId = assignedRole.id;
      if (assignedRole.isSystem && assignedRole.name === 'Organization Admin') {
        baseRole = UserRole.ORGANIZATION_ADMIN;
      }
    } else {
      const memberRole = await this.prisma.role.findFirst({
        where: { tenantId, isSystem: false },
        orderBy: { createdAt: 'asc' },
      });
      if (!memberRole) {
        throw new BadRequestException('Create a non-admin role in Roles & Permissions, then choose it for this user');
      }
      roleId = memberRole.id;
    }

    const rawToken = crypto.randomBytes(32).toString('hex');
    const invitationTokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');
    const invitationTokenExpiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days

    const user = await this.prisma.user.create({
      data: {
        tenantId,
        email,
        name: dto.name.trim(),
        role: baseRole,
        roleId,
        status: UserStatus.INVITED,
        canDelete: dto.canDelete ?? false,
        canExport: dto.canExport ?? false,
        invitationTokenHash,
        invitationTokenExpiresAt,
      },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        roleId: true,
        customRole: {
          select: {
            id: true,
            name: true,
            isSystem: true,
          },
        },
        status: true,
        canDelete: true,
        canExport: true,
        createdAt: true,
      },
    });

    const inviteLink = `${resolvePrimaryWebOrigin()}/accept-invite?token=${rawToken}`;

    const delivery = await this.emailService.sendInvitationEmail(user.email, user.name, org.name, inviteLink);

    return {
      user,
      ...inviteDeliveryResult(delivery.success, inviteLink),
    };
  }

  // Updates a member's role within the organization.
  async updateMemberRole(tenantId: string, userId: string, dto: UpdateMemberRoleDto) {
    const user = await this.prisma.user.findFirst({
      where: { id: userId, tenantId },
    });
    if (!user) {
      throw new NotFoundException('User not found');
    }

    const role = await this.prisma.role.findFirst({
      where: { id: dto.roleId, tenantId },
    });
    if (!role) {
      throw new NotFoundException('Role not found in this organization');
    }

    const nextRole = role.isSystem && role.name === 'Organization Admin' ? UserRole.ORGANIZATION_ADMIN : UserRole.ORGANIZATION_MEMBER;

    if (user.role === UserRole.ORGANIZATION_ADMIN && nextRole !== UserRole.ORGANIZATION_ADMIN) {
      const otherAdmins = await this.prisma.user.count({
        where: {
          tenantId,
          role: UserRole.ORGANIZATION_ADMIN,
          status: UserStatus.ACTIVE,
          NOT: { id: userId },
        },
      });
      if (otherAdmins === 0) {
        throw new BadRequestException('Cannot demote the only active Organization Admin. Assign another admin first.');
      }
    }

    return this.prisma.user.update({
      where: { id: userId },
      data: {
        roleId: role.id,
        role: nextRole,
      },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        roleId: true,
        customRole: {
          select: {
            id: true,
            name: true,
            isSystem: true,
            permissions: true,
          },
        },
        status: true,
      },
    });
  }

  // Updates custom delete and export permissions for an organization member.
  async updateMemberPermissions(tenantId: string, userId: string, dto: UpdateMemberPermissionsDto) {
    const user = await this.prisma.user.findFirst({
      where: { id: userId, tenantId },
    });

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

    if (user.role === UserRole.ORGANIZATION_ADMIN) {
      throw new BadRequestException('Organization Admin permissions are fixed');
    }

    return this.prisma.user.update({
      where: { id: userId },
      data: {
        canDelete: dto.canDelete !== undefined ? dto.canDelete : undefined,
        canExport: dto.canExport !== undefined ? dto.canExport : undefined,
      },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        canDelete: true,
        canExport: true,
      },
    });
  }

  // Updates user account status and increments session version on suspension.
  async updateMemberStatus(tenantId: string, userId: string, dto: UpdateMemberStatusDto) {
    const user = await this.prisma.user.findFirst({
      where: { id: userId, tenantId },
    });

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

    if (user.role === UserRole.ORGANIZATION_ADMIN) {
      throw new BadRequestException('Cannot change status of Organization Admin');
    }

    if (user.status === UserStatus.INVITED) {
      throw new BadRequestException('This person has not accepted their invitation yet');
    }

    return this.prisma.user.update({
      where: { id: userId },
      data: {
        status: dto.status,
        ...(dto.status === UserStatus.SUSPENDED ? { sessionVersion: { increment: 1 } } : {}),
      },
      select: {
        id: true,
        name: true,
        email: true,
        status: true,
      },
    });
  }
}
