<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Requests\Dashboard\ArtworkEditRequest;
use App\Http\Requests\Dashboard\ArtworkDestroyRequest;
use App\Http\Requests\Dashboard\UpdateArtworkRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ArtworkController extends Controller
{
    public function index(Request $request): View
    {
        $artworks = $request->user()
            ->artworks()
            ->latest()
            ->paginate(20);

        return view('artworks.index', [
            'artworks' => $artworks,
            'page_title' => 'My Artworks',
        ]);
    }

    public function edit(ArtworkEditRequest $request, int $id): View
    {
        $artwork = $request->artwork();

        return view('artworks.edit', [
            'artwork' => $artwork,
            'page_title' => 'Edit Artwork',
        ]);
    }

    public function update(UpdateArtworkRequest $request, int $id): RedirectResponse
    {
        $artwork = $request->artwork();

        $data = $request->validated();

        $artwork->title = $data['title'];
        $artwork->description = $data['description'] ?? null;

        if ($request->hasFile('file')) {
            $file = $request->file('file');

            // Remove prior stored file if it's on the public disk.
            if (! empty($artwork->file_path) && Storage::disk('public')->exists($artwork->file_path)) {
                Storage::disk('public')->delete($artwork->file_path);
            }

            $size = $file->getSize() ?? 0;
            $mime = $file->getMimeType() ?? 'application/octet-stream';

            $dimensions = @getimagesize($file->getRealPath());
            $width = is_array($dimensions) ? (int) ($dimensions[0] ?? 0) : 0;
            $height = is_array($dimensions) ? (int) ($dimensions[1] ?? 0) : 0;

            $path = $file->storePublicly('artworks', 'public');

            $artwork->file_name = $file->getClientOriginalName();
            $artwork->file_path = $path;
            $artwork->file_size = (int) $size;
            $artwork->mime_type = (string) $mime;
            $artwork->width = max(1, $width);
            $artwork->height = max(1, $height);

            // If a file is replaced, clear CDN-derived fields unless a separate pipeline repopulates them.
            $artwork->hash = null;
            $artwork->thumb_ext = null;
            $artwork->file_ext = $file->guessExtension() ?: $file->getClientOriginalExtension() ?: null;
        }

        $artwork->save();

        return redirect()
            ->route('dashboard.artworks.edit', $artwork->id)
            ->with('status', 'Artwork updated.');
    }

    public function destroy(ArtworkDestroyRequest $request, int $id): RedirectResponse
    {
        $artwork = $request->artwork();

        // Best-effort remove stored file.
        if (! empty($artwork->file_path) && Storage::disk('public')->exists($artwork->file_path)) {
            Storage::disk('public')->delete($artwork->file_path);
        }

        $artwork->delete();

        return redirect()
            ->route('dashboard.artworks.index')
            ->with('status', 'Artwork deleted.');
    }
}
