<?php

declare(strict_types=1);

namespace Dealerdirect\Agreements\Mailers;

use Dealerdirect\Agreements\DataObjects\PurchaseAgreement;
use Dealerdirect\Agreements\Enums\Locale;
use Dealerdirect\Agreements\Utils\GeneralUtils;
use DealerDirect\Generic\Category\EmailType;
use DealerDirect\Generic\Category\VehicleType;
use DealerDirect\Sdk\Facade\Email as EmailClient;
use Dealerdirect\Sdk\Model\Email\Attachment;
use Dealerdirect\Sdk\Model\Email\Email;
use Dealerdirect\Sdk\Model\Email\Recipient;
use Dealerdirect\Sdk\Model\Email\SubstitutionKeys;
use Dealerdirect\Sdk\Model\Email\Substitutions;
use Illuminate\Support\Arr;

/**
 * @property PurchaseAgreement $data
 */
final class PurchaseAgreementMailer extends Mailer
{
    public function getRecipients(): array
    {
        return array_map(
            fn (string $email) => new Recipient($email, $this->data->company->getName()),
            $this->data->company->getValidEmails()
        );
    }

    public function getCc(): array
    {
        return [];
    }

    public function getBcc(): array
    {
        $bcc = [];
        if (in_array($this->data->vehicleType, [VehicleType::SCOOTER, VehicleType::MOTOR], true)) {
            $bcc[] = new Recipient('kerim@dealerdirect.nl', 'Kerim Gilbers');
        } elseif (Locale::NL_NL === $this->data->locale && $this->data->salesFee >= 500) {
            $bcc[] = new Recipient('feedback@ikwilvanmijnautoaf.nl', $this->data->company->getName());
        }

        return $bcc;
    }

    public static function create(
        EmailClient $client,
        PurchaseAgreement $data,
        string $agreementPdf
    ): self {
        return new self($client, self::getEmail($data, $agreementPdf), $data);
    }

    public static function getEmail(PurchaseAgreement $data, string $agreementPdf): Email
    {
        return new Email(
            $data->locale->value,
            $data->vehicleType,
            EmailType::PURCHASE_AGREEMENT,
            self::getSubstitutions($data),
            self::getAttachments($agreementPdf, $data)
        );
    }

    /**
     * @return Attachment[]
     */
    private static function getAttachments(string $agreementPdf, PurchaseAgreement $data): array
    {
        $pdfName = GeneralUtils::getTranslator($data)->get('purchase_agreement.pdf', ['id' => $data->lotId]);

        return [
            new Attachment($agreementPdf, 'application/pdf', $pdfName),
        ];
    }

    private static function getSubstitutions(PurchaseAgreement $data): Substitutions
    {
        $translator = GeneralUtils::getTranslator($data);

        return new Substitutions([
            SubstitutionKeys::AGENT_NAME => $data->salesAgent->name,
            SubstitutionKeys::CONSUMER_ADDRESS => $data->consumer->getAddress(),
            SubstitutionKeys::CONSUMER_NAME => $data->consumer->getName(),
            SubstitutionKeys::CONSUMER_EMAIL => Arr::first($data->consumer->getValidEmails()),
            SubstitutionKeys::CONSUMER_PHONE => GeneralUtils::combinePhoneNumbers(
                $data->consumer->phoneNumbers[0] ?? '',
                $data->consumer->phoneNumbers[1] ?? '',
            ),
            SubstitutionKeys::FULL_NAME => $data->company->getName(),
            SubstitutionKeys::LOT_NUMBER => $data->lotId,

            SubstitutionKeys::VEHICLE_BODYWORK
                => $translator->get("vehicle.bodytype.{$data->vehicle->bodyType}") ?? '-',
            SubstitutionKeys::VEHICLE_CONSTRUCTION_YEAR => $data->vehicle->constructionYear,
            SubstitutionKeys::VEHICLE_CONSUMER_PRICE
                => GeneralUtils::getConsumerPrice($data->salesPrice, $data->salesFee),
            SubstitutionKeys::VEHICLE_DEALER_FEE => $data->salesFee,
            SubstitutionKeys::VEHICLE_DEALER_PICK_UP
                => GeneralUtils::translateYesNo($data->pickUp, $data->locale->value),
            SubstitutionKeys::VEHICLE_GROSS_PRICE => $data->salesPrice,
            SubstitutionKeys::VEHICLE_MAKE => $data->vehicle->brand,
            SubstitutionKeys::VEHICLE_MODEL => $data->vehicle->model,
            SubstitutionKeys::VEHICLE_MILEAGE => $data->vehicle->odometerReading,
            SubstitutionKeys::VEHICLE_REGISTRATION_PLATE => $data->vehicle->licensePlate,
            SubstitutionKeys::VEHICLE_TRIM_LEVEL => $data->vehicle->vehicleTrim,
            SubstitutionKeys::VEHICLE_DELIVERY_DATE => $data->soldDate->modify('+ 14 days')->format('d-m-Y'),

            SubstitutionKeys::LEAD_CONSUMER_LABEL_NAME
                    => GeneralUtils::getSiteDataByReference($data->siteReference, $data->vehicleType)['labelName'],
        ]);
    }
}
