<?php

namespace apexl\Io\modules\file\entities;

use apexl\entityCore\enums\Casts;
use apexl\entityCore\traits\hasCasts;
use apexl\Io\includes\Entity;
use apexl\Io\includes\System;
use apexl\Io\modules\file\entities\operators\fileOperator;
use apexl\Io\modules\file\services\File;
use DateTimeImmutable;

/**
 * @property int $id
 * @property string $name
 * @property string $path
 * @property string $mime
 * @property string $access_perm
 * @property DateTimeImmutable $created
 * @property int $created_by
 * @property DateTimeImmutable $modified
 * @property int $modified_by
 *
 * @mixin fileOperator
 */
class fileEntity extends Entity
{
    const TABLE = 'files';

    use hasCasts;

    public File $fileService;

    public function __construct()
    {
        parent::__construct(self::TABLE);
        $this->setOperator(new fileOperator(self::TABLE));
        $this->setRequiredData(['entity_id', 'entity_type', 'path']);
        $this->fileService = File::getInstance();
    }

    public function casts(): array
    {
        return [
            'id' => Casts::INT,
            'created' => Casts::DATETIME_STAMP,
            'modified' => Casts::DATETIME_STAMP,
        ];
    }

    public function downloadFilePath(): string
    {
        return $this->path;
    }

    /**
     * function to get the full local file path of the file.
     * @return string
     */
    public function getLocalPath(): string
    {
        return sprintf('%s%s%s', System::getBasePath(), DIRECTORY_SEPARATOR, $this->path);
    }

    public function delete($id = null): Entity
    {
        $path = System::getBasePath().DIRECTORY_SEPARATOR.$this->data['path'];
        //unlink the attached file
        if (file_exists($path)) {
            logger('error')->notice('Attempting to delete non-existent file at {path}', [
                'path' => $path,
            ]);
        } else {
            unlink($path);
        }

        return parent::delete($id);
    }
}
