import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { UserRole } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { CreateBackupDto } from './dto/backup.dto';

@Injectable()
export class DataBackupService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
  ) {}

  // Helpers for formatting standard ANSI SQL tenant backup scripts
  private formatSqlValue(val: unknown): string {
    if (val === null || val === undefined) return 'NULL';
    if (typeof val === 'boolean') return val ? '1' : '0';
    if (typeof val === 'number') return Number.isFinite(val) ? String(val) : 'NULL';
    if (val instanceof Date) {
      return `'${val.toISOString().slice(0, 19).replace('T', ' ')}'`;
    }
    if (Buffer.isBuffer(val) || val instanceof Uint8Array) {
      return `X'${Buffer.from(val).toString('hex')}'`;
    }
    if (typeof val === 'object') {
      return `'${this.escapeSqlString(JSON.stringify(val))}'`;
    }
    return `'${this.escapeSqlString(String(val))}'`;
  }

  private escapeSqlString(str: string): string {
    return str.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\0/g, '\\0').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replaceAll('\x1a', '\\Z');
  }

  private async getTableDdl(tableName: string): Promise<string> {
    try {
      const raw = await this.prisma.$queryRawUnsafe<any[]>(`SHOW CREATE TABLE \`${tableName}\``);
      if (raw && raw.length > 0) {
        const ddl = (raw[0]['Create Table'] || raw[0]['create table'] || Object.values(raw[0])[1]) as string;
        if (ddl) {
          return ddl.replace(/^CREATE TABLE\s+/i, 'CREATE TABLE IF NOT EXISTS ') + ';\n';
        }
      }
    } catch {
      // Fallback if query fails
    }
    return '';
  }

  private buildTableSql(tableName: string, rows: Record<string, unknown>[], ddl = ''): string {
    const parts: string[] = [`-- -------------------------------------------------------------`, `-- Table structure for \`${tableName}\``, `-- -------------------------------------------------------------`];

    if (ddl) {
      parts.push(ddl);
    }

    if (!rows || rows.length === 0) {
      parts.push(`-- Table \`${tableName}\`: 0 records to insert\n`);
      return parts.join('\n') + '\n';
    }

    parts.push(`-- Dumping data for table \`${tableName}\` (${rows.length} records)`);
    const columns = Object.keys(rows[0]);
    const colSql = columns.map((c) => `\`${c}\``).join(', ');
    const chunks: string[] = [];
    const chunkSize = 50;

    for (let i = 0; i < rows.length; i += chunkSize) {
      const slice = rows.slice(i, i + chunkSize);
      const valueTuples = slice.map((row) => {
        const vals = columns.map((col) => this.formatSqlValue(row[col]));
        return `  (${vals.join(', ')})`;
      });
      chunks.push(`INSERT INTO \`${tableName}\` (${colSql}) VALUES\n${valueTuples.join(',\n')};\n`);
    }

    parts.push(chunks.join('\n'));
    return parts.join('\n') + '\n';
  }

  // Creates a complete tenant database backup (.sql file) with full relational metadata.
  async createBackup(ctx: RequestTenantContext, actor: { role: string; canExport: boolean }, dto: CreateBackupDto) {
    if (actor.role !== UserRole.ORGANIZATION_ADMIN && !actor.canExport) {
      throw new ForbiddenException('You do not have permission to backup workspace data');
    }

    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const where = this.tenant.scopeWhere(ctx);
    const now = new Date();

    const [org, user, roles, rolePermissions, users, customers, contacts, leads, deals, dealStageHistory, projects, projectMembers, milestones, tasks, timeEntries, products, services, quotes, quoteItems, invoices, invoiceItems, payments, calendarEvents, activities, numberSequences, auditEvents] = await Promise.all([
      this.prisma.organization.findUnique({ where: { id: tenantId } }),
      ctx.userId ? this.prisma.user.findUnique({ where: { id: ctx.userId }, select: { id: true, name: true, email: true } }) : null,
      this.prisma.role.findMany({ where: { tenantId } }),
      this.prisma.rolePermission.findMany({ where: { role: { tenantId } } }),
      this.prisma.user.findMany({ where: { tenantId }, omit: { passwordHash: true, resetTokenHash: true, resetTokenExpiresAt: true, invitationTokenHash: true, invitationTokenExpiresAt: true, sessionVersion: true, failedLoginAttempts: true, lockedUntil: true } }),
      this.prisma.customer.findMany({ where }),
      this.prisma.contact.findMany({ where }),
      this.prisma.lead.findMany({ where }),
      this.prisma.deal.findMany({ where }),
      this.prisma.dealStageHistory.findMany({ where: { tenantId } }),
      this.prisma.project.findMany({ where: { tenantId } }),
      this.prisma.projectMember.findMany({ where: { tenantId } }),
      this.prisma.milestone.findMany({ where: { tenantId } }),
      this.prisma.task.findMany({ where }),
      this.prisma.timeEntry.findMany({ where: { tenantId } }),
      this.prisma.product.findMany({ where: { tenantId } }),
      this.prisma.service.findMany({ where: { tenantId } }),
      this.prisma.quote.findMany({ where: { tenantId } }),
      this.prisma.quoteItem.findMany({ where: { tenantId } }),
      this.prisma.invoice.findMany({ where: { tenantId } }),
      this.prisma.invoiceItem.findMany({ where: { tenantId } }),
      this.prisma.payment.findMany({ where: { tenantId } }),
      this.prisma.calendarEvent.findMany({ where }),
      this.prisma.activity.findMany({ where }),
      this.prisma.numberSequence.findMany({ where: { tenantId } }),
      this.prisma.auditEvent.findMany({ where: { tenantId } }),
    ]);

    const isJson = dto.format === 'json';
    const timestampStr = now.toISOString().slice(0, 19).replace(/[:T]/g, '-');
    const ext = isJson ? 'json' : 'sql';
    const fileName = `backup-${org?.name.toLowerCase().replace(/[^a-z0-9]/g, '-') || 'workspace'}-${timestampStr}.${ext}`;
    const mimeType = isJson ? 'application/json' : 'application/sql';

    const counts = {
      users: users.length,
      customers: customers.length,
      contacts: contacts.length,
      leads: leads.length,
      deals: deals.length,
      projects: projects.length,
      tasks: tasks.length,
      timeEntries: timeEntries.length,
      quotes: quotes.length,
      invoices: invoices.length,
      payments: payments.length,
    };
    const totalRecords = Object.values(counts).reduce((a, b) => a + b, 0);

    let serialized: string;

    if (isJson) {
      serialized = JSON.stringify(
        {
          metadata: {
            tenantId,
            organizationName: org?.name,
            exportedAt: now.toISOString(),
            exportedBy: user ? `${user.name} (${user.email})` : 'System',
            totalRecords,
            counts,
            formatVersion: '2.2',
          },
          data: {
            organization: org,
            roles,
            rolePermissions,
            users,
            customers,
            contacts,
            leads,
            deals,
            dealStageHistory,
            projects,
            projectMembers,
            milestones,
            tasks,
            timeEntries,
            products,
            services,
            quotes,
            quoteItems,
            invoices,
            invoiceItems,
            payments,
            calendarEvents,
            activities,
            numberSequences,
            auditEvents,
          },
        },
        null,
        2,
      );
    } else {
      const includeSchema = dto.includeSchema ?? true;
      const ddlMap: Record<string, string> = {};

      if (includeSchema) {
        const tables = [
          'organizations',
          'roles',
          'role_permissions',
          'users',
          'customers',
          'contacts',
          'leads',
          'deals',
          'deal_stage_history',
          'projects',
          'project_members',
          'milestones',
          'tasks',
          'time_entries',
          'products',
          'services',
          'quotes',
          'quote_items',
          'invoices',
          'invoice_items',
          'payments',
          'calendar_events',
          'activities',
          'number_sequences',
          'audit_events',
        ];
        await Promise.all(
          tables.map(async (t) => {
            ddlMap[t] = await this.getTableDdl(t);
          }),
        );
      }

      const sqlHeader = [
        `-- =============================================================`,
        `-- TechCMantix CRM Tenant Database Backup`,
        `-- Tenant: ${org?.name || 'Workspace'} (${tenantId})`,
        `-- Exported: ${now.toISOString()}`,
        `-- Generated By: ${user ? `${user.name} (${user.email})` : 'System'}`,
        `-- Total Records Dumped: ${totalRecords}`,
        `-- Server: MariaDB / MySQL Compatible`,
        `-- =============================================================\n`,
        `SET FOREIGN_KEY_CHECKS = 0;`,
        `SET NAMES utf8mb4;\n`,
      ].join('\n');

      const sqlParts = [
        sqlHeader,
        this.buildTableSql('organizations', org ? [org as unknown as Record<string, unknown>] : [], ddlMap['organizations']),
        this.buildTableSql('roles', roles as unknown as Record<string, unknown>[], ddlMap['roles']),
        this.buildTableSql('role_permissions', rolePermissions as unknown as Record<string, unknown>[], ddlMap['role_permissions']),
        this.buildTableSql('users', users as unknown as Record<string, unknown>[], ddlMap['users']),
        this.buildTableSql('customers', customers as unknown as Record<string, unknown>[], ddlMap['customers']),
        this.buildTableSql('contacts', contacts as unknown as Record<string, unknown>[], ddlMap['contacts']),
        this.buildTableSql('leads', leads as unknown as Record<string, unknown>[], ddlMap['leads']),
        this.buildTableSql('deals', deals as unknown as Record<string, unknown>[], ddlMap['deals']),
        this.buildTableSql('deal_stage_history', dealStageHistory as unknown as Record<string, unknown>[], ddlMap['deal_stage_history']),
        this.buildTableSql('projects', projects as unknown as Record<string, unknown>[], ddlMap['projects']),
        this.buildTableSql('project_members', projectMembers as unknown as Record<string, unknown>[], ddlMap['project_members']),
        this.buildTableSql('milestones', milestones as unknown as Record<string, unknown>[], ddlMap['milestones']),
        this.buildTableSql('tasks', tasks as unknown as Record<string, unknown>[], ddlMap['tasks']),
        this.buildTableSql('time_entries', timeEntries as unknown as Record<string, unknown>[], ddlMap['time_entries']),
        this.buildTableSql('products', products as unknown as Record<string, unknown>[], ddlMap['products']),
        this.buildTableSql('services', services as unknown as Record<string, unknown>[], ddlMap['services']),
        this.buildTableSql('quotes', quotes as unknown as Record<string, unknown>[], ddlMap['quotes']),
        this.buildTableSql('quote_items', quoteItems as unknown as Record<string, unknown>[], ddlMap['quote_items']),
        this.buildTableSql('invoices', invoices as unknown as Record<string, unknown>[], ddlMap['invoices']),
        this.buildTableSql('invoice_items', invoiceItems as unknown as Record<string, unknown>[], ddlMap['invoice_items']),
        this.buildTableSql('payments', payments as unknown as Record<string, unknown>[], ddlMap['payments']),
        this.buildTableSql('calendar_events', calendarEvents as unknown as Record<string, unknown>[], ddlMap['calendar_events']),
        this.buildTableSql('activities', activities as unknown as Record<string, unknown>[], ddlMap['activities']),
        this.buildTableSql('number_sequences', numberSequences as unknown as Record<string, unknown>[], ddlMap['number_sequences']),
        this.buildTableSql('audit_events', auditEvents as unknown as Record<string, unknown>[], ddlMap['audit_events']),
        `\nSET FOREIGN_KEY_CHECKS = 1;`,
        `-- =============================================================`,
        `-- End of Backup Dump: ${totalRecords} records written successfully`,
        `-- =============================================================\n`,
      ];

      serialized = sqlParts.join('\n');
    }

    const fileRecord = await this.prisma.file.create({
      data: {
        tenantId,
        fileName,
        mimeType,
        sizeBytes: Buffer.byteLength(serialized, 'utf8'),
        uploadedById: ctx.userId || null,
        content: {
          create: {
            bytes: new Uint8Array(Buffer.from(serialized, 'utf8')),
          },
        },
      },
    });

    return {
      id: fileRecord.id,
      fileName: fileRecord.fileName,
      sizeBytes: fileRecord.sizeBytes,
      format: isJson ? 'json' : 'sql',
      counts,
      totalRecords,
      createdAt: fileRecord.createdAt,
      uploadedBy: user,
    };
  }

  // Returns historical database backup logs for the authenticated tenant.
  async getBackupLogs(ctx: RequestTenantContext) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const records = await this.prisma.file.findMany({
      where: {
        tenantId,
        fileName: { startsWith: 'backup-' },
      },
      include: {
        uploadedBy: { select: { id: true, name: true, email: true } },
      },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });

    return records.map((r) => ({
      id: r.id,
      fileName: r.fileName,
      mimeType: r.mimeType,
      sizeBytes: r.sizeBytes,
      createdAt: r.createdAt,
      status: 'Ready',
      uploadedBy: r.uploadedBy,
    }));
  }

  // Downloads backup file bytes by ID.
  async downloadBackup(ctx: RequestTenantContext, fileId: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const record = await this.prisma.file.findFirst({
      where: { id: fileId, tenantId },
      include: { content: true },
    });

    if (!record || !record.content) {
      throw new NotFoundException('Backup file not found');
    }

    return {
      fileName: record.fileName,
      mimeType: record.mimeType,
      data: record.content.bytes,
    };
  }
}
