<?php
namespace App\Services;

use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\CsatSurvey;
use App\Models\SlaConfig;
use App\Models\ActivityLog;
use Illuminate\Support\Str;

class TicketService
{
    public function __construct(private NotificationService $notif) {}

    public function create(array $data, int $userId): Ticket
    {
        $data['ticket_number'] = Ticket::generateNumber();
        $data['created_by']    = $userId;
        $data['status']        = 'open';

        $ticket = Ticket::create($data);
        $this->applySla($ticket);

        ActivityLog::log('ticket', 'created', "Tiket #{$ticket->ticket_number} dibuat", $ticket);
        $this->notif->notifyTicketCreated($ticket->fresh()->load('client'));

        return $ticket;
    }

    public function applySla(Ticket $ticket): void
    {
        $client = $ticket->client;
        if (!$client->sla_enabled) return;

        $sla = SlaConfig::where('client_id', $client->id)->first()
            ?? SlaConfig::where('is_default', 1)->first();
        if (!$sla) return;

        $responseMin = $sla->getResponseMinutes($ticket->priority);
        $solveMin    = $sla->getSolveMinutes($ticket->priority);

        $ticket->update([
            'sla_config_id'         => $sla->id,
            'sla_response_deadline' => now()->addMinutes($responseMin),
            'sla_solve_deadline'    => now()->addMinutes($solveMin),
            'sla_status'            => 'ok',
        ]);
    }

    public function updateStatus(Ticket $ticket, string $status, ?string $resolution = null): void
    {
        $old    = $ticket->status;
        $update = ['status' => $status];

        if ($status === 'resolved') {
            $update['resolved_at']   = now();
            $update['sla_solved_at'] = now();
            if ($resolution) $update['resolution'] = $resolution;
            $this->sendCsat($ticket);
        }
        if ($status === 'closed') {
            $update['closed_at'] = now();
        }
        if ($status === 'in_progress' && !$ticket->sla_responded_at) {
            $update['sla_responded_at'] = now();
        }

        $ticket->update($update);
        ActivityLog::log('ticket', 'status_changed', "Tiket #{$ticket->ticket_number}: {$old} → {$status}", $ticket);

        if ($status === 'resolved') {
            $this->notif->notifyTicketResolved($ticket->fresh()->load('client'));
        }
    }

    private function sendCsat(Ticket $ticket): void
    {
        CsatSurvey::create([
            'ticket_id' => $ticket->id,
            'client_id' => $ticket->client_id,
            'token'     => Str::random(32),
            'channel'   => 'whatsapp',
            'sent_at'   => now(),
        ]);
    }

    public function storeAttachment(Ticket $ticket, $file, int $userId): TicketAttachment
    {
        $allowed = ['image/jpeg','image/png','application/pdf'];
        if (!in_array($file->getMimeType(), $allowed)) {
            throw new \Exception('Format file tidak didukung. Hanya JPG, PNG, PDF.');
        }
        if ($file->getSize() > 5 * 1024 * 1024) {
            throw new \Exception('Ukuran file maksimal 5MB.');
        }

        $filename = Str::uuid().'.'.$file->getClientOriginalExtension();
        $path     = $file->storeAs('ticket-attachments', $filename, 'public');

        return TicketAttachment::create([
            'ticket_id'     => $ticket->id,
            'filename'      => $filename,
            'original_name' => $file->getClientOriginalName(),
            'mime_type'     => $file->getMimeType(),
            'file_size'     => $file->getSize(),
            'path'          => $path,
            'uploaded_by'   => $userId,
        ]);
    }
}
