<?php

namespace App\Http\Controllers\Client;

use App\Enums\ActorType;
use App\Enums\DeclarationStatus;
use App\Enums\MessageType;
use App\Http\Controllers\Controller;
use App\Mail\DeclarationTextMessageMail;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Inertia\Inertia;
use Inertia\Response;

class UploadController extends Controller
{
    /**
     * Show the client upload page.
     */
    public function show(Request $request, string $token): Response
    {
        $invitation = $request->attributes->get('declaration_invitation');
        $declaration = $invitation->declaration;

        $declaration->load(['client']);
        $documents = $declaration->getMedia('documents')->map(fn ($m) => [
            'id' => $m->id,
            'name' => $m->name,
            'file_name' => $m->file_name,
            'size' => $m->human_readable_size,
            'created_at' => $m->created_at->format('d/m/Y H:i'),
        ])->values()->all();

        return Inertia::render('client/Upload', [
            'declaration' => [
                'id' => $declaration->id,
                'title' => $declaration->title,
                'client_name' => $declaration->client->company_name,
            ],
            'token' => $token,
            'documents' => $documents,
            'uploadUrl' => route('client.upload.store', ['token' => $token]),
            'csrfToken' => csrf_token(),
        ]);
    }

    /**
     * Store uploaded files.
     */
    public function store(Request $request, string $token): RedirectResponse
    {
        $invitation = $request->attributes->get('declaration_invitation');
        $declaration = $invitation->declaration;

        $request->validate([
            'files' => ['required', 'array', 'min:1'],
            'files.*' => ['file', 'max:10240'],
        ]);

        $message = $declaration->messages()->create([
            'type' => MessageType::Text,
            'body' => 'Documents déposés par le client.',
            'sent_by_type' => ActorType::Client,
            'sent_by_id' => $declaration->client_id,
            'metadata' => ['invitation_id' => $invitation->id],
        ]);

        foreach ($request->file('files') as $file) {
            $declaration->addMedia($file)
                ->withCustomProperties([
                    'message_id' => $message->id,
                    'uploaded_by_type' => ActorType::Client,
                    'uploaded_by_id' => $declaration->client_id,
                ])
                ->toMediaCollection('documents');
        }

        // Only transition to en_cours if the current status allows it
        $allowed = DeclarationStatus::allowedTransitions()[$declaration->status->value] ?? [];
        if (in_array(DeclarationStatus::EnCours, $allowed)) {
            $declaration->update(['status' => DeclarationStatus::EnCours]);
        }

        $recipient = $declaration->assignee ?? $declaration->creator;
        if ($recipient?->email) {
            Mail::to($recipient->email)->send(
                new DeclarationTextMessageMail($declaration, 'Le client a déposé des documents.', null)
            );
        }

        return back()->with('flash', ['type' => 'success', 'message' => 'Documents envoyés avec succès.']);
    }
}
