<?php

namespace App\Jobs;

use App\Models\Address;
use App\Models\Client;
use App\Models\Payment;
use App\Models\Provider;
use App\Models\Schedule;
use App\Models\User;
use App\Services\EmailService;
use App\Services\ScheduleService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class FinishScheduleJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public int $scheduleId
    ) {}

    public function handle()
    {
        try {
            $schedule = Schedule::find($this->scheduleId);

            $date_cleaned = Carbon::parse($schedule->date)->format('Y-m-d');

            if (! $schedule) {
                return;
            }

            Log::channel('schedule_end_jobs')->info('Verificando status do agendamento id: '.$schedule->id);

            Log::channel('schedule_end_jobs')->info('Status do agendamento: '.$schedule->status);

            if ($schedule->status !== 'started') {
                return;
            }

            Log::channel('schedule_end_jobs')->info('Verificando data');

            Log::channel('schedule_end_jobs')->info('Data do agendamento: '.$date_cleaned);

            Log::channel('schedule_end_jobs')->info('Data atual: '.now()->toDateString());

            if ($date_cleaned > now()->toDateString()) {
                return;
            }

            Log::channel('schedule_end_jobs')->info('Verificando horário');

            Log::channel('schedule_end_jobs')->info('Horário do agendamento: '.$schedule->end_time);

            Log::channel('schedule_end_jobs')->info('Horário atual: '.now()->toTimeString());

            $end_date_time = Carbon::parse($date_cleaned.' '.$schedule->end_time);

            if ($end_date_time > now()) {
                return;
            }

            Log::channel('schedule_end_jobs')->info('Validado com sucesso, atualizado agendamento id: '.$schedule->id.' para status finalizado');

            app(ScheduleService::class)->updateStatus($schedule->id, 'finished');

            $provider = Provider::find($schedule->provider_id);

            $provider->update([
                'total_services' => $provider->total_services + 1,
            ]);

            $client = Client::find($schedule->client_id);

            $client->update([
                'total_services' => $client->total_services + 1,
            ]);

            $emailService = new EmailService;

            $serviceAmount = (float) $schedule->total_amount;

            $payment = Payment::query()
                ->where('schedule_id', $schedule->id)
                ->whereIn('status', ['paid', 'authorized'])
                ->latest('id')
                ->first();

            $paymentMethod = $payment?->payment_method ?? 'pix';

            $platformFeeRate = $paymentMethod === 'credit_card'
                ? (float) config('services.pagarme.platform_credit_card_fee_rate')
                : (float) config('services.pagarme.platform_pix_fee_rate');

            $serviceFee = round($serviceAmount * $platformFeeRate, 2);

            $finalAmount = $serviceAmount + $serviceFee;

            $email_cliente = User::find($schedule->client->user_id)->email;

            $address = Address::find($schedule->address_id);

            $emailService->sendEmailReceipt(
                email:          $email_cliente,
                schedule:       $schedule,
                client_name:    $schedule->client->user->name,
                service_date:   $schedule->date,
                start_time:     $schedule->start_time,
                end_time:       $schedule->end_time,
                address:        $address->address.', '.$address->number.($address->has_complement ? ', '.$address->complement : '').' - '.$address->district.', '.$address->city->name.'/'.$address->state->code,
                total_amount:   $serviceAmount,
                service_fee:    $serviceFee,
                final_amount:   $finalAmount,
                payment_method: $paymentMethod === 'credit_card' ? 'Cartão de crédito' : 'PIX'
            );
        } catch (\Exception $e) {
            Log::channel('schedule_end_jobs')->error('Erro ao finalizar agendamento id: '.$this->scheduleId.'. Erro: '.$e->getMessage());

            return;
        }
    }
}
