<?php

namespace App\Notifications;

use App\Models\Leave;

class LeaveWithdrawalRequestedNotification extends HrmsNotification
{
    public function __construct(
        public Leave $leave
    ) {}

    public function notificationCategory(): string
    {
        return 'leave';
    }

    public function notificationSubject(): string
    {
        $name = $this->leave->user?->name ?? 'An employee';

        return 'Leave withdrawal requested — '.$name;
    }

    public function notificationLines(): array
    {
        $user = $this->leave->user;
        $lines = [
            ($user?->name ?? 'An employee').' requested to withdraw an approved leave.',
            'Type: '.($this->leave->leaveType?->name ?? 'Leave'),
            'Dates: '.$this->leave->start_date?->format('d M Y').' to '.$this->leave->end_date?->format('d M Y'),
        ];

        $withdrawalReason = trim((string) ($this->leave->withdrawal_reason ?? ''));
        if ($withdrawalReason !== '') {
            $lines[] = 'Reason: '.$withdrawalReason;
        }

        return $lines;
    }

    public function actionUrl(): ?string
    {
        return route('leaves.index', ['status' => 'withdrawal_pending']);
    }

    public function actionLabel(): string
    {
        return 'Review withdrawal';
    }

    public function toArray(object $notifiable): array
    {
        $user = $this->leave->user;
        $withdrawalReason = trim((string) ($this->leave->withdrawal_reason ?? ''));

        return [
            'type' => 'leave_withdrawal_requested',
            'message' => ($user?->name ?? 'An employee').' requested to withdraw leave for '
                .$this->leave->start_date?->format('d M Y').' to '.$this->leave->end_date?->format('d M Y').'.',
            'leave_id' => $this->leave->id,
            'employee_name' => $user?->name,
            'withdrawal_reason' => $withdrawalReason !== '' ? $withdrawalReason : null,
            'url' => route('leaves.index', ['status' => 'withdrawal_pending']),
        ];
    }

    protected function fcmType(): string
    {
        return 'leave_withdrawal_requested';
    }

    protected function fcmRoute(): string
    {
        return '/leave';
    }

    protected function fcmData(): array
    {
        return [
            'leave_id' => (string) $this->leave->id,
            'outcome' => 'withdrawal_pending',
        ];
    }
}
