<?php

namespace Tests\E2E\Services\Projects\Schedules;

use Tests\E2E\Client;
use Utopia\Database\Helpers\ID;
use Utopia\System\System;

trait SchedulesBase
{
    protected static array $cachedScheduleProjectData = [];

    protected function setupScheduleProjectData(): array
    {
        if (!empty(self::$cachedScheduleProjectData)) {
            return self::$cachedScheduleProjectData;
        }

        $teamId = ID::unique();
        $team = null;
        for ($i = 0; $i < 3; $i++) {
            $team = $this->client->call(Client::METHOD_POST, '/teams', array_merge([
                'content-type' => 'application/json',
                'x-appwrite-project' => $this->getProject()['$id'],
            ], $this->getHeaders()), [
                'teamId' => $teamId,
                'name' => 'Schedule Test Team',
            ]);
            if (\in_array($team['headers']['status-code'], [201, 409])) {
                break;
            }
            \usleep(500000);
        }
        $this->assertContains($team['headers']['status-code'], [201, 409]);

        $project = null;
        for ($i = 0; $i < 3; $i++) {
            $project = $this->client->call(Client::METHOD_POST, '/projects', array_merge([
                'content-type' => 'application/json',
                'x-appwrite-project' => $this->getProject()['$id'],
            ], $this->getHeaders()), [
                'projectId' => ID::unique(),
                'name' => 'Schedule Test Project',
                'teamId' => $team['body']['$id'] ?? $teamId,
                'region' => System::getEnv('_APP_REGION', 'default'),
            ]);
            if ($project['headers']['status-code'] === 201) {
                break;
            }
            \usleep(500000);
        }
        $this->assertEquals(201, $project['headers']['status-code']);

        $projectId = $project['body']['$id'];

        $key = $this->client->call(Client::METHOD_POST, '/projects/'.$projectId.'/keys', array_merge([
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()), [
            'keyId' => ID::unique(),
            'name' => 'Schedule Test Key',
            'scopes' => [
                'functions.read',
                'functions.write',
                'executions.read',
                'executions.write',
                'messages.read',
                'messages.write',
            ],
        ]);

        $this->assertEquals(201, $key['headers']['status-code']);

        self::$cachedScheduleProjectData = [
            'projectId' => $projectId,
            'apiKey' => $key['body']['secret'],
        ];

        return self::$cachedScheduleProjectData;
    }
}
