<?php

namespace App\Media\PathGenerators;

use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Support\PathGenerator\PathGenerator;

class CustomPathGenerator implements PathGenerator
{
    public function getPath(Media $media): string
    {
        $s3Key = $media->getCustomProperty('s3_key');

        if ($s3Key) {
            return dirname($s3Key).'/';
        }

        if (str_contains($media->file_name, '/')) {
            return '';
        }

        $model = $media->model;

        if ($model && method_exists($model, 'getMediaPath')) {
            return $model->getMediaPath($media).'/';
        }

        return $this->defaultPath($media);
    }

    public function getPathForConversions(Media $media): string
    {
        $s3Key = $media->getCustomProperty('s3_key');
        $dir = $s3Key ? dirname($s3Key).'/' : $this->defaultPath($media);

        return $dir.'conversions/';
    }

    public function getPathForResponsiveImages(Media $media): string
    {
        $s3Key = $media->getCustomProperty('s3_key');
        $dir = $s3Key ? dirname($s3Key).'/' : $this->defaultPath($media);

        return $dir.'responsive/';
    }

    private function defaultPath(Media $media): string
    {
        $moduleMap = [
            'UserProfile' => 'user-profile',
            'Attendance' => 'attendance',
            'SystemConfiguration' => 'setting',
            'HomepageConfiguration' => 'homepage',
            'ProductVariant' => 'product',
            'Cutting' => 'cutting',
            'RawMaterialPrice' => 'raw-material',
            'CashTransaction' => 'cash',
            'Expense' => 'expense',
            'Order' => 'order',
            'Restock' => 'restock',
            'Purchase' => 'purchase',
            'OwnerVerificationRequest' => 'owner_verification_request',
        ];

        $modelClass = class_basename($media->model_type);
        $module = $moduleMap[$modelClass] ?? strtolower($modelClass);
        $collection = $media->collection_name;
        $date = $media->created_at->format('Y-m-d');
        $id = $media->model_id;

        return "{$module}/{$collection}/{$date}/{$id}/";
    }
}
