import { Body, Controller, Param, Post } from '@nestjs/common';
import { ShootingRepo } from '../../repos/shooting.repo';
import {
  assertRessourceExists,
  assertValuesAreDefined,
} from '@/core/functions/assert';
import { EmailSender } from '@/modules/emails/services/email-sender';
import { ShareShootingDTO } from '@studio-m/app-types';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { CurrentUser } from '@/models/users/decorators/current-user';
import { User } from '@/models/users/domain/user';
import { buildShootingShareEmail } from '@/modules/emails/templates/shooting-share.template';

@Controller('shootings')
export class ShareShooting {
  constructor(
    private shootingRepo: ShootingRepo,
    private emailSender: EmailSender,
    private eventEmitter: EventEmitter2,
  ) {}

  @Post(':id/share')
  async execute(
    @Param('id') id: string,
    @Body() { emails, name, message }: ShareShootingDTO,
    @CurrentUser() user: User,
  ) {
    const sharedMessage = message || '';
    assertRessourceExists(emails?.length);
    assertValuesAreDefined(emails);

    const shooting = await this.shootingRepo.findById(id);
    assertRessourceExists(shooting);
    assertRessourceExists(shooting.customer);

    const customerEmail = shooting.customer?.email;
    const recipients = [];
    const senderFullName = [user.firstname, user.lastname]
      .filter(Boolean)
      .join(' ')
      .trim();
    const deliveries: {
      mode: 'customer' | 'guest';
      recipients: { email: string; name?: string }[];
      params: {
        shootingName: string;
        shootingUrl: string;
        message: string;
        page: 'shooting';
      };
      template: {
        subject: string;
        previewText: string;
      };
      html: string;
    }[] = [];
    let htmlContent: string | null = null;

    const createUrl = (mode: string) =>
      `${process.env.FRONT_SITE}/shootings/${id}/view?customerId=${shooting.customer.id}&mode=${mode}`;

    const sendEmail = async (
      emailList: string[],
      mode: 'customer' | 'guest',
    ) => {
      const emailRecipients = emailList.map((email) => ({
        email,
        name: name || email,
      }));
      const shootingUrl = createUrl(mode);
      const rendered = await this.emailSender.sendShootingShareHtmlEmail(
        emailRecipients,
        {
          shootingName: shooting.name,
          shootingUrl,
          message: sharedMessage,
          senderName: senderFullName || undefined,
          page: 'shooting',
        },
        {
          replyTo: {
            email: user.email,
            name: senderFullName || undefined,
          },
        },
      );
      recipients.push(...emailRecipients);
      if (!htmlContent || mode === 'guest') {
        htmlContent = rendered.html;
      }
      deliveries.push({
        mode,
        recipients: emailRecipients,
        params: {
          shootingName: shooting.name,
          shootingUrl,
          message: sharedMessage,
          page: 'shooting',
        },
        template: {
          subject: rendered.subject,
          previewText: rendered.previewText,
        },
        html: rendered.html,
      });
    };

    if (customerEmail && emails.includes(customerEmail)) {
      await sendEmail([customerEmail], 'customer');
      const guestEmails = emails.filter((email) => email !== customerEmail);
      if (guestEmails.length) await sendEmail(guestEmails, 'guest');
    } else {
      await sendEmail(emails, 'guest');
    }

    this.eventEmitter.emit('shooting.shared', {
      user,
      shooting,
      recipients,
      message: sharedMessage,
      deliveries,
      sender: {
        name: senderFullName || undefined,
        email: user.email,
      },
      htmlContent,
      customerId: shooting.customer.id,
    });

    return { success: true };
  }

  @Post(':id/share/preview')
  async preview(
    @Param('id') id: string,
    @Body()
    {
      message,
      mode,
      sender,
    }: ShareShootingDTO & {
      mode?: 'customer' | 'guest';
      sender?: { name?: string };
    },
    @CurrentUser() user: User,
  ) {
    const sharedMessage = message || '';
    const shooting = await this.shootingRepo.findById(id);
    assertRessourceExists(shooting);
    assertRessourceExists(shooting.customer);

    const previewMode = mode === 'customer' ? 'customer' : 'guest';

    const createUrl = (targetMode: string) =>
      `${process.env.FRONT_SITE}/shootings/${id}/view?customerId=${shooting.customer.id}&mode=${targetMode}`;

    const senderFullName = [user.firstname, user.lastname]
      .filter(Boolean)
      .join(' ')
      .trim();
    const resolvedSenderName = sender?.name || senderFullName || undefined;

    const shootingUrl =
      previewMode === 'customer' && shooting.customer?.email
        ? createUrl('customer')
        : createUrl('guest');

    return buildShootingShareEmail({
      shootingName: shooting.name,
      shootingUrl,
      message: sharedMessage,
      senderName: resolvedSenderName,
      page: 'shooting',
    });
  }
}
