<?php

namespace App\Services;

use App\Mail\PendataanPegawaiSubmitted;
use App\Models\Pegawai;
use App\Models\UnitKerja;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Throwable;

class PegawaiEmailService
{
    public function send(Pegawai $pegawai, string $mode = 'submitted', ?array $loginAccount = null): void
    {
        if (config('mail.default') === 'log') {
            Mail::to($pegawai->email)->send(new PendataanPegawaiSubmitted($pegawai, $mode, $loginAccount));

            $pegawai->update([
                'email_status' => 'logged',
                'email_sent_at' => null,
                'email_error' => 'MAIL_MAILER masih log, email belum dikirim melalui Gmail.',
            ]);

            return;
        }

        try {
            Mail::to($pegawai->email)->send(new PendataanPegawaiSubmitted($pegawai, $mode, $loginAccount));

            $pegawai->update([
                'email_status' => 'sent',
                'email_sent_at' => now(),
                'email_error' => null,
            ]);
        } catch (Throwable $exception) {
            $pegawai->update([
                'email_status' => 'failed',
                'email_sent_at' => null,
                'email_error' => $exception->getMessage(),
            ]);
        }
    }

    public function createLoginAccount(Pegawai $pegawai): array
    {
        $password = Str::random(10) . '1!';
        $unitKerja = UnitKerja::where('nama_unit', $pegawai->unit_kerja)->first();

        User::updateOrCreate(
            ['pegawai_id' => $pegawai->id],
            [
                'name' => $pegawai->nama_lengkap,
                'email' => $pegawai->email,
                'password' => Hash::make($password),
                'role' => 'pegawai',
                'unit_kerja_id' => $unitKerja?->id,
                'must_change_password' => true,
                'email_verified_at' => now(),
            ]
        );

        return [
            'password' => $password,
        ];
    }
}
