<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\View\View;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Booking;
use Mtc\MercuryDataModels\Enquiry;
use Mtc\MercuryDataModels\Invoice;

class DocsController extends Controller
{
    /**
     * API docs page
     * @return View
     */
    public function swagger()
    {
        return view('docs.swagger');
    }

    /**
     * Email preview
     *
     * @return View
     */
    public function mail()
    {
        return view('docs.mail', [
            'mailables' => collect(config('mail.preview_mailables'))
                ->map(fn($class, $name) => str_replace('-', ' ', Str::title($name)))
        ]);
    }

    /**
     * Preview single email
     *
     * @param string $mailable
     * @return mixed
     */
    public function viewMail(string $mailable)
    {
        $class = config("mail.preview_mailables.$mailable");

        return match ($mailable) {
            'invoice-notification', 'overdue-invoice-notification' => $this->invoiceMail($class),
            'new-service-booking', 'new-service-booking-confirmation' => $this->bookingMail($class),
            'enquiry', 'enquiry-customer-copy' => $this->enquiryMail($class),
        };
    }

    /**
     * Create mail with dummy data
     *
     * @param $mail_object
     * @return mixed
     */
    private function invoiceMail($mail_object)
    {
        $invoice = Invoice::factory()->make();
        return new $mail_object($invoice);
    }

    private function bookingMail($mail_object)
    {
        if (session()->has('current_tenant')) {
            tenancy()->initialize(session('current_tenant'));
        }
        $booking = Booking::query()->inRandomOrder()->first();
        if (!$booking) {
            $booking = Booking::factory()->make();
        }
        return new $mail_object($booking);
    }

    private function enquiryMail($mail_object)
    {
        if (session()->has('current_tenant')) {
            tenancy()->initialize(session('current_tenant'));
            $enquiry = Enquiry::query()->first();
        }
        if (empty($enquiry)) {
            $enquiry = Enquiry::factory()->make();
        }
        return new $mail_object($enquiry);
    }
}
