import type {ExtendedEvent, ShortEvent, SWEvent} from "../types/event.js";
import {fetchWithToken} from "./repo.js";
import type {Moment} from "moment";
import {ExtendedEventSchema, ShortEventSchema, SWEventSchema} from "../types/event.js";
import {z} from "zod";

export interface CreateEvent {
    name: string
    start: Moment
    end: Moment
}

export interface UpdateEvent {
    name: string
    start: Moment
    end: Moment
    deadline: Moment
    maxTeamMembers: number
    schemType: string | null
    publicSchemsOnly: boolean
    spectateSystem: boolean
}

export class EventRepo {
    constructor(private token: string) {}

    public async listEvents(): Promise<ShortEvent[]> {
        return await fetchWithToken(this.token, "/events")
            .then(value => value.json())
            .then(value => z.array(ShortEventSchema).parse(value));
    }

    public async getEvent(id: string): Promise<ExtendedEvent> {
        return await fetchWithToken(this.token, `/events/${id}`)
            .then(value => value.json())
            .then(ExtendedEventSchema.parse);
    }

    public async createEvent(event: CreateEvent): Promise<SWEvent> {
        return await fetchWithToken(this.token, "/events", {
            method: "POST",
            body: JSON.stringify({
                name: event.name,
                start: +event.start,
                end: +event.end
            }),
        }).then(value => value.json())
            .then(SWEventSchema.parse);
    }

    public async updateEvent(id: string, event: UpdateEvent): Promise<SWEvent> {
        return await fetchWithToken(this.token, `/events/${id}`, {
            method: "PUT",
            body: JSON.stringify({
                name: event.name,
                start: +event.start,
                end: +event.end,
                deadline: +event.deadline,
                maxTeamMembers: event.maxTeamMembers,
                schemType: event.schemType,
                publicSchemsOnly: event.publicSchemsOnly,
                spectateSystem: event.spectateSystem
            }),
            headers: {
                "Content-Type": "application/json"
            }
        }).then(value => value.json())
            .then(SWEventSchema.parse);
    }

    public async deleteEvent(id: string): Promise<boolean> {
        const res = await fetchWithToken(this.token, `/events/${id}`, {
            method: "DELETE"
        });

        return res.ok;
    }
}
