<?php

namespace Modules\MedNotify\Database\Seeders;

use Illuminate\Database\Seeder;
use Modules\MedNotify\Entities\MednotifyTemplate;

/**
 * Seeds a SYSTEM DEFAULT template (business_id NULL) for each of the 5 seeded
 * events × 4 channels, with sensible bodies using {variable} placeholders.
 * A tenant edit creates a business override; reset-to-default deletes it and
 * these rows take over again. Idempotent via updateOrCreate on
 * (business_id NULL, event_key, channel).
 */
class MednotifyTemplatesSeeder extends Seeder
{
    public function run(): void
    {
        foreach ($this->templates() as $tpl) {
            MednotifyTemplate::updateOrCreate(
                ['business_id' => null, 'event_key' => $tpl['event_key'], 'channel' => $tpl['channel']],
                [
                    'subject' => $tpl['subject'],
                    'body'    => $tpl['body'],
                    'enabled' => true,
                ]
            );
        }
    }

    /**
     * One entry per event × channel. subject only for in_app + email.
     *
     * @return array<int, array<string, mixed>>
     */
    private function templates(): array
    {
        $rows = [];

        $defs = [
            'appointment.created' => [
                'subject' => 'Appointment confirmed',
                'body'    => 'Hi {contact_name}, your appointment with {doctor_name} at {facility_name} is scheduled for {appointment_date}.',
            ],
            'lab.result.ready' => [
                'subject' => 'Lab result ready',
                'body'    => 'The result for {test_name} (order {order_no}) for {patient_name} is now ready.',
            ],
            'prescription.ready' => [
                'subject' => 'Prescription ready',
                'body'    => 'Hi {contact_name}, prescription {rx_no} is ready at {pharmacy_name}.',
            ],
            'invoice.overdue' => [
                'subject' => 'Invoice {invoice_no} is overdue',
                'body'    => 'Dear {contact_name}, invoice {invoice_no} for {amount_due} was due on {due_date}. Please settle it at your earliest convenience.',
            ],
            'bed.available' => [
                'subject' => 'Bed available',
                'body'    => 'Bed {bed_no} in {ward_name} is now available for {patient_name}.',
            ],
        ];

        foreach ($defs as $eventKey => $def) {
            foreach (['in_app', 'email', 'sms', 'whatsapp'] as $channel) {
                $subject = in_array($channel, ['in_app', 'email'], true) ? $def['subject'] : null;

                $rows[] = [
                    'event_key' => $eventKey,
                    'channel'   => $channel,
                    'subject'   => $subject,
                    'body'      => $def['body'],
                ];
            }
        }

        return $rows;
    }
}
