import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Organization, OrganizationStatus, Prisma, User, UserRole, UserStatus } from '@prisma/client';
import * as crypto from 'crypto';
import ExcelJS from 'exceljs';
import { inviteDeliveryResult } from '../../common/utils/invite-response';
import { resolvePrimaryWebOrigin } from '../../common/utils/web-origin';
import { PrismaService } from '../../prisma/prisma.service';
import { EmailService } from '../email/email.service';
import { CreateOrganizationDto } from './dto/create-organization.dto';
import { InviteOrgAdminDto } from './dto/invite-org-admin.dto';
import { UpdateOrganizationDto } from './dto/update-organization.dto';
import { UpdateOrgStatusDto } from './dto/update-org-status.dto';
import { ExportOrganizationsQuery } from './dto/export-organizations.query';
import { ListAuditLogsQuery } from './dto/list-audit-logs.query';

const INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const ORG_NOT_FOUND = 'Organization not found';
const primaryAdminSelect = { id: true, name: true, email: true, role: true, status: true, createdAt: true } satisfies Prisma.UserSelect;

/** Creates a single-use invitation token; only its SHA-256 hash is stored. */
function newInviteToken() {
  const rawToken = crypto.randomBytes(32).toString('hex');
  return {
    rawToken,
    invitationTokenHash: crypto.createHash('sha256').update(rawToken).digest('hex'),
    invitationTokenExpiresAt: new Date(Date.now() + INVITE_TTL_MS),
  };
}

/** Escapes LIKE wildcards so % and _ in a search are matched literally (Prisma's contains does not escape them on MySQL). */
function escapeLike(text: string): string {
  return text.replace(/[\\%_]/g, (c) => `\\${c}`);
}

/** True when a Prisma error is a unique-constraint violation. */
function isUniqueViolation(err: unknown): boolean {
  return err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002';
}

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

  /** Lists every organization with its user count and first (primary) organization admin. */
  async listOrganizations() {
    const orgs = await this.prisma.organization.findMany({
      include: {
        _count: { select: { users: true } },
        users: { where: { role: UserRole.ORGANIZATION_ADMIN }, select: primaryAdminSelect, orderBy: { createdAt: 'asc' }, take: 1 },
      },
      orderBy: { createdAt: 'desc' },
    });

    return orgs.map((org) => ({
      id: org.id,
      name: org.name,
      phone: org.phone,
      city: org.city,
      status: org.status,
      createdAt: org.createdAt,
      updatedAt: org.updatedAt,
      admin: org.users[0] ?? null,
      stats: { usersCount: org._count.users },
    }));
  }

  /** Returns one organization with its primary admin and recent platform activity on the org or its users. */
  async getOrganization(id: string) {
    const org = await this.prisma.organization.findUnique({
      where: { id },
      include: {
        users: { where: { role: UserRole.ORGANIZATION_ADMIN }, select: primaryAdminSelect, orderBy: { createdAt: 'asc' }, take: 1 },
        _count: { select: { users: true } },
      },
    });
    if (!org) throw new NotFoundException(ORG_NOT_FOUND);

    const userIds = (await this.prisma.user.findMany({ where: { tenantId: id }, select: { id: true } })).map((u) => u.id);
    const auditLogs = await this.prisma.platformAuditLog.findMany({
      where: { targetId: { in: [id, ...userIds] } },
      orderBy: { createdAt: 'desc' },
      take: 20,
      include: { actor: { select: { id: true, name: true, email: true, role: true } } },
    });

    return {
      id: org.id,
      name: org.name,
      phone: org.phone,
      city: org.city,
      status: org.status,
      createdAt: org.createdAt,
      updatedAt: org.updatedAt,
      admin: org.users[0] ?? null,
      stats: { usersCount: org._count.users },
      auditLogs,
    };
  }

  /** Rejects a name already used by another organization (comparison follows the database collation, so it ignores case). */
  private async assertUniqueName(name: string, exceptId?: string): Promise<void> {
    const clash = await this.prisma.organization.findFirst({ where: { name, ...(exceptId ? { id: { not: exceptId } } : {}) }, select: { id: true } });
    if (clash) throw new ConflictException(`An organization named "${name}" already exists`);
  }

  /** Rejects an email that already belongs to any user on the platform. */
  private async assertEmailFree(email: string, exceptUserId?: string): Promise<void> {
    const clash = await this.prisma.user.findFirst({ where: { email, ...(exceptUserId ? { id: { not: exceptUserId } } : {}) }, select: { id: true } });
    if (clash) throw new ConflictException(`A user with email "${email}" already exists`);
  }

  /** Emails an invitation link and reports delivery without exposing the link once email works. */
  private async sendInvite(email: string, name: string, orgName: string, rawToken: string) {
    const inviteLink = `${resolvePrimaryWebOrigin()}/accept-invite?token=${rawToken}`;
    const delivery = await this.emailService.sendInvitationEmail(email, name, orgName, inviteLink);
    return inviteDeliveryResult(delivery.success, inviteLink);
  }

  /** Creates an organization and its invited root admin in one transaction, then emails the invitation. */
  async createOrganization(dto: CreateOrganizationDto, actorId: string, ipAddress?: string) {
    await this.assertUniqueName(dto.name);
    await this.assertEmailFree(dto.adminEmail);
    const token = newInviteToken();

    let result: { org: Organization; admin: User };
    try {
      result = await this.prisma.$transaction(async (tx) => {
        const org = await tx.organization.create({ data: { name: dto.name, phone: dto.phone, city: dto.city ?? null } });
        const admin = await tx.user.create({
          data: {
            name: dto.adminName,
            email: dto.adminEmail,
            role: UserRole.ORGANIZATION_ADMIN,
            status: UserStatus.INVITED,
            tenantId: org.id,
            canDelete: true,
            canExport: true,
            invitationTokenHash: token.invitationTokenHash,
            invitationTokenExpiresAt: token.invitationTokenExpiresAt,
          },
        });
        await tx.platformAuditLog.create({
          data: {
            actorId,
            action: 'CREATE_ORG',
            targetType: 'ORGANIZATION',
            targetId: org.id,
            ipAddress: ipAddress || null,
            metadata: { organizationName: org.name, phone: org.phone, city: org.city, adminName: admin.name, adminEmail: admin.email },
          },
        });
        return { org, admin };
      });
    } catch (err) {
      if (isUniqueViolation(err)) throw new ConflictException(`A user with email "${dto.adminEmail}" already exists`);
      throw err;
    }

    const delivery = await this.sendInvite(result.admin.email, result.admin.name, result.org.name, token.rawToken);
    return {
      organization: {
        id: result.org.id,
        name: result.org.name,
        phone: result.org.phone,
        city: result.org.city,
        status: result.org.status,
        createdAt: result.org.createdAt,
        updatedAt: result.org.updatedAt,
        stats: { usersCount: 1 },
      },
      admin: { id: result.admin.id, name: result.admin.name, email: result.admin.email, role: result.admin.role, status: result.admin.status },
      ...delivery,
    };
  }

  /** Suspends or reactivates an organization; repeating the current status changes nothing and logs nothing. */
  async updateOrganizationStatus(id: string, dto: UpdateOrgStatusDto, actorId: string, ipAddress?: string) {
    const org = await this.prisma.organization.findUnique({ where: { id } });
    if (!org) throw new NotFoundException(ORG_NOT_FOUND);
    if (org.status === dto.status) return org;

    const action = dto.status === OrganizationStatus.SUSPENDED ? 'SUSPEND_ORG' : 'UNSUSPEND_ORG';
    return this.prisma.$transaction(async (tx) => {
      const updated = await tx.organization.update({ where: { id }, data: { status: dto.status } });
      await tx.platformAuditLog.create({
        data: { actorId, action, targetType: 'ORGANIZATION', targetId: org.id, ipAddress: ipAddress || null, metadata: { organizationName: org.name, previousStatus: org.status, newStatus: dto.status } },
      });
      return updated;
    });
  }

  /** Updates the organization profile and its primary admin; an admin email can change only before the invitation is accepted. */
  async updateOrganization(id: string, dto: UpdateOrganizationDto, actorId: string, ipAddress?: string) {
    const org = await this.prisma.organization.findUnique({ where: { id } });
    if (!org) throw new NotFoundException(ORG_NOT_FOUND);
    const admin = await this.prisma.user.findFirst({ where: { tenantId: id, role: UserRole.ORGANIZATION_ADMIN }, orderBy: { createdAt: 'asc' } });

    const orgChanges: { name?: string; phone?: string; city?: string | null } = {};
    if (dto.name !== undefined && dto.name !== org.name) orgChanges.name = dto.name;
    if (dto.phone !== undefined && dto.phone !== org.phone) orgChanges.phone = dto.phone;
    if (dto.city !== undefined && (dto.city ?? null) !== org.city) orgChanges.city = dto.city ?? null;

    const adminChanges: { name?: string; email?: string } = {};
    if (admin && dto.adminName !== undefined && dto.adminName !== admin.name) adminChanges.name = dto.adminName;
    if (admin && dto.adminEmail !== undefined && dto.adminEmail !== admin.email) adminChanges.email = dto.adminEmail;
    if (!admin && (dto.adminName !== undefined || dto.adminEmail !== undefined)) {
      throw new BadRequestException('This organization has no admin yet. Use "Invite admin" instead.');
    }

    if (orgChanges.name) await this.assertUniqueName(orgChanges.name, id);
    if (adminChanges.email) {
      if (admin!.status !== UserStatus.INVITED) {
        throw new BadRequestException('The admin has already activated their account, so their sign-in email cannot be changed here.');
      }
      await this.assertEmailFree(adminChanges.email, admin!.id);
    }
    if (Object.keys(orgChanges).length === 0 && Object.keys(adminChanges).length === 0) return org;

    const token = adminChanges.email ? newInviteToken() : null;
    let updated: typeof org;
    try {
      updated = await this.prisma.$transaction(async (tx) => {
        const saved = Object.keys(orgChanges).length ? await tx.organization.update({ where: { id }, data: orgChanges }) : org;
        if (Object.keys(adminChanges).length) {
          await tx.user.update({
            where: { id: admin!.id },
            data: { ...adminChanges, ...(token ? { invitationTokenHash: token.invitationTokenHash, invitationTokenExpiresAt: token.invitationTokenExpiresAt } : {}) },
          });
        }
        await tx.platformAuditLog.create({
          data: {
            actorId,
            action: 'UPDATE_ORG_PROFILE',
            targetType: 'ORGANIZATION',
            targetId: org.id,
            ipAddress: ipAddress || null,
            metadata: {
              organizationName: saved.name,
              previous: { name: org.name, phone: org.phone, city: org.city, ...(admin ? { adminName: admin.name, adminEmail: admin.email } : {}) },
              updated: { ...orgChanges, ...(adminChanges.name ? { adminName: adminChanges.name } : {}), ...(adminChanges.email ? { adminEmail: adminChanges.email } : {}) },
            },
          },
        });
        return saved;
      });
    } catch (err) {
      if (isUniqueViolation(err)) throw new ConflictException(`A user with email "${adminChanges.email}" already exists`);
      throw err;
    }

    if (token && adminChanges.email) {
      const delivery = await this.sendInvite(adminChanges.email, adminChanges.name ?? admin!.name, updated.name, token.rawToken);
      return { ...updated, invitation: delivery };
    }
    return updated;
  }

  /** Invites (or re-invites) an organization admin with a fresh 7-day link; suspended organizations cannot invite. */
  async inviteFirstOrgAdmin(orgId: string, dto: InviteOrgAdminDto, actorId: string, ipAddress?: string) {
    const org = await this.prisma.organization.findUnique({ where: { id: orgId } });
    if (!org) throw new NotFoundException(ORG_NOT_FOUND);
    if (org.status === OrganizationStatus.SUSPENDED) {
      throw new BadRequestException('Reactivate this organization before inviting an admin.');
    }

    const existingUser = await this.prisma.user.findUnique({ where: { email: dto.email } });
    if (existingUser && !(existingUser.tenantId === org.id && existingUser.status === UserStatus.INVITED && existingUser.role === UserRole.ORGANIZATION_ADMIN)) {
      throw new ConflictException(`A user with email "${dto.email}" already exists`);
    }
    const token = newInviteToken();

    let user: User;
    try {
      user = await this.prisma.$transaction(async (tx) => {
        const target = existingUser
          ? await tx.user.update({ where: { id: existingUser.id }, data: { name: dto.name, invitationTokenHash: token.invitationTokenHash, invitationTokenExpiresAt: token.invitationTokenExpiresAt } })
          : await tx.user.create({
              data: {
                tenantId: org.id,
                email: dto.email,
                name: dto.name,
                role: UserRole.ORGANIZATION_ADMIN,
                status: UserStatus.INVITED,
                canDelete: true,
                canExport: true,
                invitationTokenHash: token.invitationTokenHash,
                invitationTokenExpiresAt: token.invitationTokenExpiresAt,
              },
            });
        await tx.platformAuditLog.create({
          data: {
            actorId,
            action: existingUser ? 'RESEND_ORG_ADMIN_INVITE' : 'INVITE_ORG_ADMIN',
            targetType: 'USER',
            targetId: target.id,
            ipAddress: ipAddress || null,
            metadata: { organizationId: org.id, organizationName: org.name, email: target.email, name: target.name },
          },
        });
        return target;
      });
    } catch (err) {
      if (isUniqueViolation(err)) throw new ConflictException(`A user with email "${dto.email}" already exists`);
      throw err;
    }

    const delivery = await this.sendInvite(user.email, user.name, org.name, token.rawToken);
    return {
      user: { id: user.id, name: user.name, email: user.email, role: user.role, status: user.status, tenantId: user.tenantId, createdAt: user.createdAt },
      ...delivery,
    };
  }

  /** Finds audit entries whose stored details (organization, names, emails) contain the text, ignoring case; % and _ are matched literally. */
  private async auditIdsWithMetadataLike(term: string): Promise<string[]> {
    const pattern = `%${escapeLike(term.toLowerCase())}%`;
    const rows = await this.prisma.$queryRaw<Array<{ id: string }>>`SELECT id FROM platform_audit_logs WHERE LOWER(CAST(metadata AS CHAR)) LIKE ${pattern} LIMIT 5000`;
    return rows.map((r) => r.id);
  }

  /** Returns one page of the full platform audit trail, newest first, filtered by action and a search over actor, organization, email and IP. */
  async listAuditLogPage(query: ListAuditLogsQuery) {
    const term = query.q?.trim();
    const like = term ? escapeLike(term) : '';
    const metadataMatches = term ? await this.auditIdsWithMetadataLike(term) : [];
    const where: Prisma.PlatformAuditLogWhereInput = {
      ...(query.action ? { action: query.action } : {}),
      ...(term
        ? {
            OR: [{ action: { contains: like } }, { ipAddress: { contains: like } }, { targetId: term }, { actor: { OR: [{ name: { contains: like } }, { email: { contains: like } }] } }, { id: { in: metadataMatches } }],
          }
        : {}),
    };
    const [total, items] = await Promise.all([
      this.prisma.platformAuditLog.count({ where }),
      this.prisma.platformAuditLog.findMany({
        where,
        orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
        skip: (query.page - 1) * query.pageSize,
        take: query.pageSize,
        include: { actor: { select: { id: true, name: true, email: true, role: true } } },
      }),
    ]);
    return { items, total, page: query.page, pageSize: query.pageSize };
  }

  /** Returns the most recent platform audit entries (1–200). */
  async listAuditLogs(limit: number = 100) {
    return this.prisma.platformAuditLog.findMany({
      take: Math.min(Math.max(Math.trunc(limit) || 100, 1), 200),
      orderBy: { createdAt: 'desc' },
      include: { actor: { select: { id: true, name: true, email: true, role: true } } },
    });
  }

  /** Exports up to 2,000 platform audit entries to an Excel (.xlsx) file. */
  async exportAuditLogsExcel(): Promise<{ filename: string; buffer: Buffer }> {
    const logs = await this.prisma.platformAuditLog.findMany({
      orderBy: { createdAt: 'desc' },
      take: 2000,
      include: {
        actor: {
          select: {
            name: true,
            email: true,
            role: true,
          },
        },
      },
    });

    const headers = ['Timestamp (UTC)', 'Timestamp (Local Display)', 'Actor Name', 'Actor Email', 'Actor Role', 'Action', 'Target Type', 'Target Description', 'Target ID', 'IP Address', 'Details / Metadata'];

    const rows = logs.map((log) => {
      let targetDesc = '';
      const meta = (log.metadata as Record<string, unknown>) || null;
      if (meta && typeof meta.name === 'string') {
        targetDesc = `${log.targetType || 'Record'}: ${meta.name}`;
      } else if (meta && typeof meta.email === 'string') {
        targetDesc = `${log.targetType || 'User'}: ${meta.email}`;
      } else if (log.targetType || log.targetId) {
        targetDesc = `${log.targetType || 'Target'} (${log.targetId?.slice(0, 8) || '—'})`;
      } else {
        targetDesc = '—';
      }

      return [log.createdAt.toISOString(), log.createdAt.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }), log.actor?.name || 'System', log.actor?.email || '—', log.actor?.role || '—', log.action, log.targetType || '—', targetDesc, log.targetId || '—', log.ipAddress || '—', log.metadata ? JSON.stringify(log.metadata) : ''];
    });

    const workbook = new ExcelJS.Workbook();
    const ws = workbook.addWorksheet('Platform Audit Logs');
    ws.addRow(headers);
    for (const r of rows) {
      ws.addRow(r);
    }
    const buffer = Buffer.from(await workbook.xlsx.writeBuffer());

    const filename = `platform-audit-logs-${new Date().toISOString().slice(0, 10)}.xlsx`;
    return { filename, buffer };
  }

  /** Exports organizations to an Excel (.xlsx) file: only the given ids when provided, otherwise all of them. */
  async exportOrganizationsExcel(query: ExportOrganizationsQuery = {}): Promise<{ filename: string; buffer: Buffer }> {
    const where: Prisma.OrganizationWhereInput = query.ids?.length ? { id: { in: query.ids } } : {};
    const orgs = await this.prisma.organization.findMany({
      where,
      include: {
        _count: {
          select: { users: true },
        },
        users: {
          where: { role: UserRole.ORGANIZATION_ADMIN },
          select: { name: true, email: true, status: true },
          orderBy: { createdAt: 'asc' },
          take: 1,
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    const headers = ['Organization Name', 'Phone', 'City', 'Status', 'Users Count', 'Primary Admin Name', 'Primary Admin Email', 'Admin Status', 'Created At', 'Last Updated'];

    const rows = orgs.map((org) => {
      const primaryAdmin = org.users[0];
      return [org.name, org.phone || '—', org.city || '—', org.status, org._count.users, primaryAdmin?.name || '—', primaryAdmin?.email || '—', primaryAdmin?.status || '—', org.createdAt.toISOString(), org.updatedAt.toISOString()];
    });

    const workbook = new ExcelJS.Workbook();
    const ws = workbook.addWorksheet('Organizations');
    ws.addRow(headers);
    for (const r of rows) {
      ws.addRow(r);
    }
    const buffer = Buffer.from(await workbook.xlsx.writeBuffer());

    const filename = `platform-organizations-${new Date().toISOString().slice(0, 10)}.xlsx`;
    return { filename, buffer };
  }
}
