<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Attachment\StoreAttachmentRequest;
use App\Http\Requests\Attachment\UpdateAttachmentRequest;
use App\Http\Resources\UserAttachmentResource;
use App\Models\UserAttachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AttachmentController extends Controller
{
    public function index(Request $request)
    {
        $attachments = UserAttachment::where('user_id', $request->user()->id)
            ->orderBy('type')
            ->orderBy('created_at', 'desc')
            ->get();

        return $this->success(UserAttachmentResource::collection($attachments));
    }

    public function store(StoreAttachmentRequest $request)
    {
        $file = $request->file('file');
        $path = $file->store('attachments/' . $request->user()->id);

        $attachment = UserAttachment::create([
            'user_id'         => $request->user()->id,
            'type'            => $request->type,
            'document_number' => $request->document_number,
            'full_name'       => $request->full_name,
            'dob'             => $request->dob,
            'expiry_date'     => $request->expiry_date,
            'nationality'     => $request->nationality,
            'issuing_country' => $request->issuing_country,
            'file_path'       => $path,
            'file_type'       => $file->getClientOriginalExtension(),
        ]);

        return $this->created(
            new UserAttachmentResource($attachment),
            'Document uploaded successfully.'
        );
    }

    public function update(UpdateAttachmentRequest $request, UserAttachment $attachment)
    {
        if ($attachment->user_id !== $request->user()->id) {
            return $this->forbidden();
        }

        $attachment->update($request->validated());

        return $this->success(
            new UserAttachmentResource($attachment->fresh()),
            'Document updated.'
        );
    }

    public function destroy(Request $request, UserAttachment $attachment)
    {
        if ($attachment->user_id !== $request->user()->id) {
            return $this->forbidden();
        }

        Storage::delete($attachment->file_path);
        $attachment->delete();

        return $this->noContent('Document removed.');
    }
}
