<?php

namespace App\Http\Controllers;

use App\Http\Requests\SpecDocumentRequest;
use App\Http\Requests\StoreSpecDocumentAttachment;
use App\Http\Resources\SpecDocumentAttachmentResource;
use App\Models\SpecDocument;
use App\Models\SpecDocumentAttachment;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;

class SpecDocumentAttachmentController extends Controller
{
    public function store(
        StoreSpecDocumentAttachment $request,
        SpecDocument $specDocument
    ): SpecDocumentAttachmentResource {
        abort_if($specDocument->isSignedOff(), 403, 'Spec document has been signed off and is read-only.');

        $sectionId = $request->input('spec_document_section_id');
        if ($sectionId) {
            abort_if(!$specDocument->sections()->whereKey($sectionId)->exists(), 404);
        }

        $file = $request->file('file');
        $path = Storage::disk(Config::get('filesystems.default_media'))
            ->putFile('spec-documents/' . $specDocument->id, $file, ['visibility' => 'public']);

        $attachment = $specDocument->attachments()->create([
            'spec_document_section_id' => $sectionId,
            'name' => $file->getClientOriginalName(),
            'path' => $path,
            'mime_type' => $file->getClientMimeType(),
            'size' => $file->getSize(),
            'created_by' => Auth::id(),
        ]);

        return new SpecDocumentAttachmentResource($attachment);
    }

    public function destroy(
        SpecDocumentRequest $request,
        SpecDocument $specDocument,
        SpecDocumentAttachment $attachment
    ): Response {
        abort_if($attachment->spec_document_id !== $specDocument->id, 404);
        abort_if($specDocument->isSignedOff(), 403, 'Spec document has been signed off and is read-only.');

        Storage::disk(Config::get('filesystems.default_media'))->delete($attachment->path);
        $attachment->delete();

        return response()->noContent();
    }
}
