<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Helpers\UploadHelper;
use App\Models\AttachmentModel;
use App\Services\ActivityLogger;

final class AttachmentController extends BaseController
{
    private const ALLOWED_ENTITY_TYPES = ['lead', 'customer', 'company'];

    public function store(Request $request): Response
    {
        $entityType = (string) $request->input('entity_type');
        $entityId = (int) $request->input('entity_id');

        if (!in_array($entityType, self::ALLOWED_ENTITY_TYPES, true) || $entityId <= 0) {
            return AjaxResponse::error('Invalid entity reference.', 422);
        }

        $file = $request->file('file');
        if ($file === null) {
            return AjaxResponse::error('No file was uploaded.', 422);
        }

        $uploader = UploadHelper::make();
        $stored = $uploader->store($file, 'attachments');
        if ($stored === null) {
            return AjaxResponse::error('Upload failed.', 422, $uploader->errors());
        }

        $model = new AttachmentModel();
        $id = $model->insert([
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'disk_path' => $stored['disk_path'],
            'original_name' => $stored['original_name'],
            'mime_type' => $stored['mime_type'],
            'size_bytes' => $stored['size_bytes'],
            'checksum_sha256' => $stored['checksum_sha256'],
            'uploaded_by' => $this->currentUserId(),
        ]);

        ActivityLogger::record($entityType, $entityId, 'file_uploaded', "Uploaded \"{$stored['original_name']}\"");

        return AjaxResponse::created($model->find($id), 'File uploaded.');
    }

    public function index(Request $request, array $params): Response
    {
        if (!in_array($params['entityType'], self::ALLOWED_ENTITY_TYPES, true)) {
            return AjaxResponse::error('Invalid entity type.', 422);
        }

        $rows = (new AttachmentModel())->forEntity($params['entityType'], (int) $params['entityId']);

        return AjaxResponse::success($rows);
    }

    public function destroy(Request $request, array $params): Response
    {
        (new AttachmentModel())->delete((int) $params['id']);

        return AjaxResponse::success(null, 'File deleted.');
    }
}
