<?php

use App\Services\FileStorageService;
use CodeIgniter\HTTP\Files\UploadedFile;
use CodeIgniter\HTTP\ResponseInterface;

if (!function_exists('storage')) {
    function storage(): FileStorageService
    {
        return service('fileStorage');
    }
}

if (!function_exists('storage_upload_if_valid')) {
    function storage_upload_if_valid(?UploadedFile $file, string $module, string $subFolder = ''): ?string
    {
        if ($file === null || ! $file->isValid() || $file->hasMoved()) {
            return null;
        }

        return storage()->uploadModuleFile($file, $module, $subFolder);
    }
}

if (!function_exists('storage_exists')) {
    function storage_exists(string $module, string $subFolder, string $fileName): bool
    {
        return $fileName !== '' && storage()->exists($module, $subFolder, $fileName);
    }
}

if (!function_exists('storage_download')) {
    function storage_download(string $module, string $subFolder, string $fileName): ResponseInterface
    {
        return storage()->download($module, $subFolder, $fileName);
    }
}

if (!function_exists('storage_inline')) {
    function storage_inline(string $module, string $subFolder, string $fileName): ResponseInterface
    {
        return storage()->download($module, $subFolder, $fileName)
            ->setHeader('Content-Disposition', 'inline; filename="' . $fileName . '"');
    }
}

if (!function_exists('storage_temporary_url')) {
    function storage_temporary_url(string $module, string $subFolder, string $fileName): string
    {
        return storage()->getTemporaryUrl($module, $subFolder, $fileName);
    }
}

if (!function_exists('storage_local_path')) {
    function storage_local_path(string $module, string $subFolder, string $fileName): string
    {
        return storage()->getLocalPathForProcessing($module, $subFolder, $fileName);
    }
}

if (!function_exists('storage_cleanup_temp')) {
    /**
     * Remove an S3 downloadToTemp working copy under the OS temp dir.
     * Safe no-op for local writable paths and missing files.
     */
    function storage_cleanup_temp(?string $path): bool
    {
        return storage()->cleanupTempPath($path);
    }
}

if (!function_exists('storage_delete')) {
    function storage_delete(string $module, string $subFolder, string $fileName): bool
    {
        return storage()->delete($module, $subFolder, $fileName);
    }
}

if (!function_exists('storage_put')) {
    function storage_put(string $module, string $subFolder, string $fileName, string $contents, array $options = []): string
    {
        return storage()->put(storage()->resolveKey($module, $subFolder, $fileName), $contents, $options);
    }
}

if (!function_exists('storage_read')) {
    function storage_read(string $module, string $subFolder, string $fileName): string
    {
        return storage()->read($module, $subFolder, $fileName);
    }
}

if (!function_exists('policy_file_type_map')) {
    /**
     * @return array<string, array{column: string, folder: string}>
     */
    function policy_file_type_map(): array
    {
        return [
            'policy_pdf'             => ['column' => 'policy_pdf_file_name', 'folder' => 'policy_pdf'],
            'policy_payment_receipt' => ['column' => 'policy_payment_receipt_file_name', 'folder' => 'policy_payment_receipt'],
        ];
    }
}

if (!function_exists('policy_upload_pdf')) {
    function policy_upload_pdf(?UploadedFile $file): ?string
    {
        return storage_upload_if_valid($file, 'policy', 'policy_pdf');
    }
}

if (!function_exists('policy_upload_receipt')) {
    function policy_upload_receipt(?UploadedFile $file): ?string
    {
        return storage_upload_if_valid($file, 'policy', 'policy_payment_receipt');
    }
}

if (!function_exists('policy_exists_by_type')) {
    function policy_exists_by_type(string $fileName, string $fileType): bool
    {
        $map = policy_file_type_map();

        if (! isset($map[$fileType])) {
            return false;
        }

        return storage_exists('policy', $map[$fileType]['folder'], $fileName);
    }
}

if (!function_exists('policy_download_by_type')) {
    function policy_download_by_type(string $fileName, string $fileType, bool $inline = false): ResponseInterface
    {
        $map = policy_file_type_map();

        if (! isset($map[$fileType])) {
            throw new InvalidArgumentException('Invalid policy file type');
        }

        $folder = $map[$fileType]['folder'];

        return $inline
            ? storage_inline('policy', $folder, $fileName)
            : storage_download('policy', $folder, $fileName);
    }
}

if (!function_exists('policy_local_pdf_path')) {
    function policy_local_pdf_path(string $fileName): string
    {
        return storage_local_path('policy', 'policy_pdf', $fileName);
    }
}

if (!function_exists('policy_md_file_name')) {
    function policy_md_file_name(string $pdfFileName): string
    {
        $mdFileName = preg_replace('/\.pdf$/i', '.md', $pdfFileName);

        if ($mdFileName === $pdfFileName) {
            $mdFileName .= '.md';
        }

        return $mdFileName;
    }
}

if (!function_exists('policy_put_md')) {
    function policy_put_md(string $fileName, string $contents): string
    {
        return storage_put('policy', 'policy_md', $fileName, $contents, ['content_type' => 'text/markdown']);
    }
}

if (!function_exists('policy_read_md')) {
    function policy_read_md(string $fileName): string
    {
        return storage_read('policy', 'policy_md', $fileName);
    }
}

if (!function_exists('policy_md_exists')) {
    function policy_md_exists(string $fileName): bool
    {
        return storage_exists('policy', 'policy_md', $fileName);
    }
}

if (!function_exists('endorsement_upload_original')) {
    function endorsement_upload_original(?UploadedFile $file): ?string
    {
        return storage_upload_if_valid($file, 'endorsement', '');
    }
}

if (!function_exists('endorsement_upload_completion')) {
    function endorsement_upload_completion(?UploadedFile $file): ?string
    {
        return storage_upload_if_valid($file, 'endorsement', 'endorsement_pdf');
    }
}

if (!function_exists('endorsement_subfolder_for_type')) {
    function endorsement_subfolder_for_type(?string $type): string
    {
        return ($type === 'completion') ? 'endorsement_pdf' : '';
    }
}

if (!function_exists('endorsement_exists_by_type')) {
    function endorsement_exists_by_type(string $fileName, ?string $type = 'original'): bool
    {
        return storage_exists('endorsement', endorsement_subfolder_for_type($type), $fileName);
    }
}

if (!function_exists('endorsement_download_by_type')) {
    function endorsement_download_by_type(string $fileName, ?string $type = 'original', bool $inline = false): ResponseInterface
    {
        $folder = endorsement_subfolder_for_type($type);

        return $inline
            ? storage_inline('endorsement', $folder, $fileName)
            : storage_download('endorsement', $folder, $fileName);
    }
}

if (!function_exists('endorsement_delete_completion')) {
    function endorsement_delete_completion(string $fileName): bool
    {
        return storage_delete('endorsement', 'endorsement_pdf', $fileName);
    }
}
