<?php

namespace App\Http\Controllers;

use App\Enums\SpecDocumentSectionType;
use App\Http\Requests\StoreSpecDocumentSection;
use App\Http\Requests\UpdateSpecDocumentSection;
use App\Http\Resources\SpecDocumentSectionResource;
use App\Models\SpecDocument;
use App\Models\SpecDocumentSection;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Mtc\MercuryDataModels\Tenant;

class SpecDocumentSectionController extends Controller
{
    use \App\Http\Controllers\Concerns\SyncsSpecDocumentTenantFields;

    public function store(StoreSpecDocumentSection $request, SpecDocument $specDocument): SpecDocumentSectionResource
    {
        abort_if($specDocument->isSignedOff(), 403, 'Spec document has been signed off and is read-only.');

        $section = $specDocument->sections()->create([
            'type' => $request->input('type'),
            'title' => $request->input('title'),
            'data' => $request->input('data'),
            'sort_order' => ((int) $specDocument->sections()->max('sort_order')) + 10,
        ]);

        return new SpecDocumentSectionResource($section);
    }

    public function update(
        UpdateSpecDocumentSection $request,
        SpecDocument $specDocument,
        SpecDocumentSection $section
    ): SpecDocumentSectionResource {
        abort_if($section->spec_document_id !== $specDocument->id, 404);
        abort_if($specDocument->isSignedOff(), 403, 'Spec document has been signed off and is read-only.');

        $section->fill($request->safe()->only(['title', 'sort_order']));

        if ($request->has('data')) {
            $section->data = $this->persistTenantFields($specDocument, $section, $request->input('data'));
        }

        if ($request->has('completed')) {
            $section->completed_at = $request->boolean('completed') ? ($section->completed_at ?? now()) : null;
            $section->completed_by = $request->boolean('completed') ? ($section->completed_by ?? Auth::id()) : null;
        }

        $section->save();
        $this->hydrateSection($section, Tenant::query()->find($specDocument->tenant_id));

        return new SpecDocumentSectionResource($section);
    }

    public function destroy(
        UpdateSpecDocumentSection $request,
        SpecDocument $specDocument,
        SpecDocumentSection $section
    ): Response {
        abort_if($section->spec_document_id !== $specDocument->id, 404);
        abort_if($specDocument->isSignedOff(), 403, 'Spec document has been signed off and is read-only.');
        abort_if(
            $section->type !== SpecDocumentSectionType::CUSTOM->value,
            422,
            'Only custom sections can be removed.'
        );

        $section->delete();

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