<?php
declare(strict_types=1);

namespace App\Controllers\Api;

use App\Middleware\ApiToken;
use App\Middleware\TenantScope;
use App\Models\Attachment;
use Core\Controller;

/**
 * Mobile-friendly attachment upload — accepts multipart/form-data with:
 *   file        (the photo/pdf/etc)
 *   owner_type  (asset | incident | work_order | expense | reading_session | round_run_stop)
 *   owner_id    (numeric)
 *   caption     (optional)
 */
final class AttachmentsController extends Controller
{
    public function middleware(): array
    {
        return [ApiToken::class, TenantScope::class];
    }

    public function upload(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            $this->json(['error' => 'POST required'], 405);
        }

        $ownerType = (string) ($_POST['owner_type'] ?? '');
        $ownerId   = (int) ($_POST['owner_id'] ?? 0);
        $caption   = $_POST['caption'] ?? null;

        if (!in_array($ownerType, Attachment::OWNERS, true) || $ownerId <= 0) {
            $this->json(['error' => 'owner_type + owner_id required'], 422);
        }
        if (empty($_FILES['file'])) {
            $this->json(['error' => 'file field required (multipart/form-data)'], 422);
        }

        $tenantId = (int) ($_SESSION['tenant_id'] ?? 0);
        $userId   = (int) ($_SESSION['user']['user_id'] ?? 0);

        try {
            $stored = Attachment::moveUploaded($ownerType, $_FILES['file']);
            $id     = Attachment::create($tenantId, $userId, $ownerType, $ownerId, $stored, $caption);
        } catch (\Throwable $e) {
            $this->json(['error' => 'Upload failed: ' . $e->getMessage()], 500);
        }

        $this->json([
            'success'       => true,
            'attachment_id' => $id,
            'file_name'     => $stored['file_name'],
            'size_bytes'    => $stored['size_bytes'] ?? null,
        ], 201);
    }

    public function list(): void
    {
        $ownerType = (string) ($_GET['owner_type'] ?? '');
        $ownerId   = (int) ($_GET['owner_id'] ?? 0);
        if (!in_array($ownerType, Attachment::OWNERS, true) || $ownerId <= 0) {
            $this->json(['error' => 'owner_type + owner_id required'], 422);
        }
        $tenantId = (int) ($_SESSION['tenant_id'] ?? 0);
        $this->json(['data' => Attachment::forOwner($tenantId, $ownerType, $ownerId)]);
    }
}
