<?php

namespace Licenzo\Services\Media;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class WordPressMediaLibraryReleaseMediaAdapter implements ReleaseMediaAdapterInterface
{
    public const PROVIDER = 'wordpress_media_library';

    public function provider(): string
    {
        return static::PROVIDER;
    }

    public function normalizeReference(array $reference): array
    {
        $attachmentId = isset($reference['attachment_id']) ? absint($reference['attachment_id']) : 0;
        if ($attachmentId <= 0 && isset($reference['id'])) {
            $attachmentId = absint($reference['id']);
        }

        if ($attachmentId <= 0) {
            throw new \InvalidArgumentException('A valid WordPress media attachment ID is required.');
        }

        $attachment = get_post($attachmentId);
        if (!$attachment || $attachment->post_type !== 'attachment') {
            throw new \InvalidArgumentException('Attachment not found in WordPress media library.');
        }

        $fileUrl = wp_get_attachment_url($attachmentId);
        if (!is_string($fileUrl) || trim($fileUrl) === '') {
            throw new \RuntimeException('Unable to resolve media attachment URL.');
        }

        $fileUrl = esc_url_raw($fileUrl);
        $filePath = get_attached_file($attachmentId);
        $fileName = basename((string) ($filePath ?: wp_parse_url($fileUrl, PHP_URL_PATH) ?: 'package.zip'));
        $mimeType = (string) get_post_mime_type($attachmentId);
        $fileSize = null;

        if (is_string($filePath) && $filePath !== '' && file_exists($filePath) && is_readable($filePath)) {
            $size = filesize($filePath);
            if ($size !== false) {
                $fileSize = (int) $size;
            }
        }

        $downloadName = sanitize_file_name((string) ($reference['download_name'] ?? ''));
        if ($downloadName === '') {
            $downloadName = sanitize_file_name($fileName);
        }

        return [
            'provider' => static::PROVIDER,
            'attachment_id' => $attachmentId,
            'file_url' => $fileUrl,
            'file_name' => $fileName,
            'download_name' => $downloadName,
            'mime_type' => $mimeType,
            'file_size' => $fileSize,
            'attachment_title' => sanitize_text_field((string) get_the_title($attachmentId)),
            'updated_at' => gmdate('Y-m-d H:i:s'),
        ];
    }

    public function resolvePublicUrl(array $media): string
    {
        $provider = (string) ($media['provider'] ?? '');
        if ($provider !== '' && $provider !== static::PROVIDER) {
            throw new \InvalidArgumentException('Unsupported media provider for WordPress adapter.');
        }

        $attachmentId = absint($media['attachment_id'] ?? 0);
        if ($attachmentId > 0) {
            $url = wp_get_attachment_url($attachmentId);
            if (is_string($url) && trim($url) !== '') {
                return esc_url_raw($url);
            }
        }

        $url = esc_url_raw((string) ($media['file_url'] ?? ''));
        if ($url === '') {
            throw new \RuntimeException('Release package URL could not be resolved.');
        }

        return $url;
    }
}
