<?php

namespace Convoy\Repositories\Eloquent;

use Carbon\Carbon;
use Convoy\Models\Backup;
use Convoy\Models\Server;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;

class BackupRepository extends EloquentRepository
{
    public function model()
    {
        return Backup::class;
    }

    /**
     * Determines if too many backups have been generated by the server.
     *
     * @return \Pterodactyl\Models\Backup[]|Collection
     */
    public function getBackupsGeneratedDuringTimespan(int $server, int $seconds = 600)
    {
        return $this->getBuilder()
            ->withTrashed()
            ->where('server_id', $server)
            ->where(function ($query) {
                $query->whereNull('completed_at')
                    ->orWhere('is_successful', '=', true);
            })
            ->where('created_at', '>=', Carbon::now()->subSeconds($seconds)->toDateTimeString())
            ->get()
            ->toBase();
    }

    public function getNonFailedBackups(Server $server): HasMany
    {
        return $server->backups()->where(function ($query) {
            $query->whereNull('completed_at')
                ->orWhere('is_successful', true);
        });
    }
}
