<?php

namespace App\Http\Controllers\Ticket;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Ticket\IndexTicketRequest;
use App\Http\Requests\Ticket\StoreTicketRequest;
use App\Http\Requests\Ticket\UpdateTicketRequest;
use App\Http\Resources\Ticket\TicketResource;
use App\Models\Ticket;
use App\Services\Ticket\TicketService;

class TicketController extends ApiController
{
    public function __construct(
        protected TicketService $service
    ) {}

    public function index(IndexTicketRequest $request)
    {
        $filters = $request->validated();
        $tickets = Ticket::query()
            ->when(
                ! empty($filters['search']),
                fn ($query) => $query->where(function ($searchQuery) use ($filters) {
                    $searchQuery->where('ticket_no', 'ILIKE', "%{$filters['search']}%")
                        ->orWhere('title', 'ILIKE', "%{$filters['search']}%")
                        ->orWhere('description', 'ILIKE', "%{$filters['search']}%");
                })
            )
            ->when(
                ! empty($filters['status']),
                fn ($query) => $query->where('status', $filters['status'])
            )
            ->when(
                ! empty($filters['priority']),
                fn ($query) => $query->where('priority', $filters['priority'])
            )
            ->when(
                ! empty($filters['ticket_type_id']),
                fn ($query) => $query->where('ticket_type_id', $filters['ticket_type_id'])
            )
            ->when(
                ! empty($filters['customer_id']),
                fn ($query) => $query->where('customer_id', $filters['customer_id'])
            )
            ->latest()
            ->paginate($filters['per_page'] ?? 10);

        return $this->successPaginated(
            $tickets,
            TicketResource::class,
            'Data Ticket berhasil diambil'
        );
    }

    public function store(StoreTicketRequest $request)
    {
        $ticket = $this->service->create(
            $request->validated()
        );

        return $this->created(
            new TicketResource($ticket),
            'Ticket berhasil dibuat'
        );
    }

    public function show(Ticket $ticket)
    {
        return $this->success(
            new TicketResource($ticket)
        );
    }

    public function update(
        UpdateTicketRequest $request,
        Ticket $ticket
    ) {
        $ticket = $this->service->update(
            $ticket,
            $request->validated()
        );

        return $this->updated(
            new TicketResource($ticket),
            'Ticket berhasil diperbarui'
        );
    }

    public function destroy(Ticket $ticket)
    {
        $this->service->delete($ticket);

        return $this->deleted(
            'Ticket berhasil dibatalkan'
        );
    }
}
