import { Body, Controller, Post } from '@nestjs/common';
import { UserActivityRepo } from '@/models/users/repos/user-activity.repo';
import { UserActivity } from '@/models/users/domain/user-activity';
import {
  EmailLogDTO,
  SearchEmailLogDTO,
  EmailLogDeliveryDTO,
  EmailLogShootingDTO,
  EmailLogCustomerDTO,
  EmailLogRecipientDTO,
} from '@studio-m/app-types';

@Controller('emails')
export class SearchEmailLogs {
  constructor(private readonly userActivityRepo: UserActivityRepo) {}

  @Post('search')
  async execute(@Body() body: SearchEmailLogDTO): Promise<EmailLogDTO[]> {
    const activities = await this.userActivityRepo.searchEmailLogs(body);
    const emailLogs = activities.map((activity) => mapActivityToEmailLog(activity));

    const q = body.q?.trim().toLowerCase();
    if (!q) {
      return emailLogs;
    }

    return emailLogs.filter((log) => matchesQuery(log, q));
  }
}

const mapActivityToEmailLog = (activity: UserActivity): EmailLogDTO => {
  const metadata = (activity.metadata || {}) as Record<string, any>;
  const shooting = extractShooting(metadata?.shooting);
  const customer =
    extractCustomer(metadata?.customer) ??
    (shooting?.customer ? { ...shooting.customer } : null);

  const deliveries = Array.isArray(metadata.deliveries)
    ? metadata.deliveries
        .filter(
          (delivery): delivery is Record<string, any> =>
            !!delivery && typeof delivery === 'object',
        )
        .map((delivery) => normalizeDelivery(delivery))
    : [];

  const recipientCandidates = [
    ...normalizeRecipients(metadata.recipients),
    ...deliveries.flatMap((delivery) => delivery.recipients),
  ];
  const recipients = dedupeRecipients(recipientCandidates);

  const sender = normalizeSender(metadata?.sender);

  const message =
    typeof metadata?.message === 'string' ? metadata.message : null;

  const inferredCustomerId =
    customer?.id ||
    metadata.customerId ||
    (activity.action === 'CUSTOMER_GALLERY_SHARED_BY_EMAIL'
      ? activity.entityId
      : null);

  return {
    id: activity.id,
    action: activity.action,
    entityId: activity.entityId,
    customerId: inferredCustomerId,
    createdAt: activity.createdAt.toISOString(),
    sender,
    message,
    recipients,
    deliveries,
    htmlContent: activity.htmlContent || null,
    shooting,
    customer,
  };
};

const matchesQuery = (log: EmailLogDTO, query: string) => {
  const haystacks: string[] = [];

  if (log.action) haystacks.push(log.action);
  if (log.message) haystacks.push(log.message);
  if (log.sender?.name) haystacks.push(log.sender.name);
  if (log.sender?.email) haystacks.push(log.sender.email);
  if (log.htmlContent) haystacks.push(log.htmlContent);
  if (log.shooting?.name) haystacks.push(log.shooting.name);
  if (log.shooting?.customer?.firstname)
    haystacks.push(log.shooting.customer.firstname);
  if (log.shooting?.customer?.lastname)
    haystacks.push(log.shooting.customer.lastname);

  log.recipients.forEach((recipient) => {
    if (recipient.email) haystacks.push(recipient.email);
    if (recipient.name) haystacks.push(recipient.name);
  });
  if (log.customer?.firstname) haystacks.push(log.customer.firstname);
  if (log.customer?.lastname) haystacks.push(log.customer.lastname);
  if (log.customer?.email) haystacks.push(log.customer.email);

  log.deliveries.forEach((delivery) => {
    if (delivery.subject) haystacks.push(delivery.subject);
    if (delivery.previewText) haystacks.push(delivery.previewText);
    if (delivery.html) haystacks.push(delivery.html);
    if (delivery.params) {
      haystacks.push(JSON.stringify(delivery.params));
    }
    delivery.recipients.forEach((recipient) => {
      if (recipient.email) haystacks.push(recipient.email);
      if (recipient.name) haystacks.push(recipient.name);
    });
  });

  return haystacks.some((value) =>
    typeof value === 'string' && value.toLowerCase().includes(query),
  );
};

const normalizeRecipients = (value: unknown): EmailLogRecipientDTO[] => {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .map((recipient) => normalizeRecipient(recipient))
    .filter((recipient): recipient is EmailLogRecipientDTO => recipient !== null);
};

const normalizeRecipient = (value: unknown): EmailLogRecipientDTO | null => {
  if (!value || typeof value !== 'object') {
    return null;
  }

  const candidate = value as Record<string, any>;
  const email =
    typeof candidate.email === 'string'
      ? candidate.email
      : candidate.email !== undefined
        ? String(candidate.email)
        : null;

  if (!email) {
    return null;
  }

  const recipient: EmailLogRecipientDTO = {
    email,
  };

  if (typeof candidate.name === 'string') {
    recipient.name = candidate.name;
  } else if (candidate.name !== undefined) {
    recipient.name = String(candidate.name);
  }

  return recipient;
};

const dedupeRecipients = (
  recipients: EmailLogRecipientDTO[],
): EmailLogRecipientDTO[] => {
  const seen = new Set<string>();
  const result: EmailLogRecipientDTO[] = [];

  recipients.forEach((recipient) => {
    const key = recipient.email.trim().toLowerCase();
    if (seen.has(key)) {
      return;
    }
    seen.add(key);
    result.push(recipient);
  });

  return result;
};

const normalizeDelivery = (delivery: Record<string, any>): EmailLogDeliveryDTO => {
  const template = typeof delivery.template === 'object' ? delivery.template : {};
  const subject =
    typeof delivery.subject === 'string'
      ? delivery.subject
      : typeof template?.subject === 'string'
        ? template.subject
        : undefined;
  const previewText =
    typeof delivery.previewText === 'string'
      ? delivery.previewText
      : typeof template?.previewText === 'string'
         ? template.previewText
         : undefined;

  const recipients = normalizeRecipients(delivery.recipients);

  const params =
    delivery.params && typeof delivery.params === 'object'
      ? delivery.params
      : undefined;

  return {
    mode:
      typeof delivery.mode === 'string'
        ? delivery.mode
        : delivery.mode !== undefined
          ? String(delivery.mode)
          : undefined,
    recipients,
    subject,
    previewText,
    html: delivery.html ?? null,
    params,
  };
};

const normalizeSender = (value: unknown): EmailLogDTO['sender'] => {
  if (!value || typeof value !== 'object') {
    return null;
  }

  const candidate = value as Record<string, any>;
  const email =
    typeof candidate.email === 'string'
      ? candidate.email
      : candidate.email !== undefined
        ? String(candidate.email)
        : null;

  if (!email) {
    return null;
  }

  const sender: EmailLogDTO['sender'] = { email };

  if (typeof candidate.name === 'string') {
    sender.name = candidate.name;
  } else if (candidate.name !== undefined) {
    sender.name = String(candidate.name);
  }

  return sender;
};

const extractShooting = (value: any): EmailLogShootingDTO | null => {
  if (!value || typeof value !== 'object') {
    return null;
  }

  const id =
    typeof value.id === 'string'
      ? value.id
      : value.id !== undefined
        ? String(value.id)
          : null;

  if (!id) {
    return null;
  }

  const shooting: EmailLogShootingDTO = {
    id,
    name:
      typeof value.name === 'string'
        ? value.name
        : value.name !== undefined
          ? String(value.name)
          : '',
    customerId:
      typeof value.customerId === 'string'
        ? value.customerId
        : value.customerId !== undefined
          ? String(value.customerId)
          : undefined,
    customer: null,
  };

  const customer = extractCustomer(value.customer);
  if (customer) {
    shooting.customer = customer;
    shooting.customerId = shooting.customerId ?? customer.id;
  } else if (value.customer === null) {
    shooting.customer = null;
  }

  return shooting;
};

const extractCustomer = (value: any): EmailLogCustomerDTO | null => {
  if (!value || typeof value !== 'object') {
    return null;
  }

  const id =
    typeof value.id === 'string'
      ? value.id
      : value.id !== undefined
        ? String(value.id)
        : null;

  if (!id) {
    return null;
  }

  const customer: EmailLogCustomerDTO = {
    id,
    firstname:
      typeof value.firstname === 'string'
        ? value.firstname
        : value.firstname !== undefined
          ? String(value.firstname)
          : '',
    lastname:
      typeof value.lastname === 'string'
        ? value.lastname
        : value.lastname !== undefined
          ? String(value.lastname)
          : '',
  };

  if (typeof value.email === 'string') {
    customer.email = value.email;
  } else if (value.email !== undefined) {
    customer.email = String(value.email);
  }

  return customer;
};
