<?php

namespace App\Http\Controllers;

use App\Http\Requests\ApproveProfileMediaRequest;
use App\Http\Requests\MediaRequest;
use App\Http\Requests\PendingProfileMediaRequest;
use App\Http\Resources\MediaResource;
use App\Services\MediaService;
use Illuminate\Http\JsonResponse;

class MediaController extends Controller
{
    public function __construct(protected MediaService $service) {}

    public function index(): JsonResponse
    {
        $items = $this->service->getAll();

        return $this->successResponse(
            payload: MediaResource::collection($items),
        );
    }

    public function store(MediaRequest $request): JsonResponse
    {
        $item = $this->service->create($request->validated());

        return $this->successResponse(
            payload: new MediaResource($item),
            message: __('messages.created'),
            code:    201,
        );
    }

    public function show(int $id): JsonResponse
    {
        $item = $this->service->findById($id);

        return $this->successResponse(payload: new MediaResource($item));
    }

    public function update(MediaRequest $request, int $id): JsonResponse
    {
        $item = $this->service->update($id, $request->validated());

        return $this->successResponse(
            payload: new MediaResource($item),
            message: __('messages.updated'),
        );
    }

    public function destroy(int $id): JsonResponse
    {
        $this->service->delete($id);

        return $this->successResponse(
            message: __('messages.deleted'),
            code:    204,
        );
    }

    //

    public function pendingProfiles(PendingProfileMediaRequest $request): JsonResponse
    {
        $paginated = $this->service->getPendingProfileMedia(
            page:    $request->integer('page', 1),
            perPage: $request->integer('per_page', 10),
        );

        return $this->successResponse(payload: [
            'data'  => MediaResource::collection($paginated->items()),
            'total' => $paginated->total(),
            'from'  => $paginated->firstItem() ?? 0,
            'to'    => $paginated->lastItem()  ?? 0,
        ]);
    }

    public function approveProfile(ApproveProfileMediaRequest $request): JsonResponse
    {
        $media = $this->service->approveProfileMedia(
            source:   $request->validated('source'),
            sourceId: $request->integer('source_id'),
        );

        return $this->successResponse(
            payload: new MediaResource($media),
            message: __('messages.updated'),
        );
    }
}
