import type {EventFight} from "../types/event.js";
import {fetchWithToken} from "./repo.js";
import type {Moment} from "moment";
import {z} from "zod";
import {EventFightSchema} from "../types/event.js";

export interface CreateFight {
    spielmodus: string
    map: string
    blueTeam: number
    redTeam: number
    start: Moment
    kampfleiter: number | null
    group: string | null
}

export interface UpdateFight {
    spielmodus: string | null
    map: string | null
    blueTeam: number | null
    redTeam: number | null
    start: Moment | null
    kampfleiter: number | null
    group: string | null
}

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

    public async listFights(eventId: number): Promise<EventFight[]> {
        return await fetchWithToken(this.token, `/events/${eventId}/fights`)
            .then(value => value.json())
            .then(value => z.array(EventFightSchema).parse(value));
    }

    public async createFight(eventId: number, fight: CreateFight): Promise<EventFight> {
        return await fetchWithToken(this.token, `/fights`, {
            method: "POST",
            body: JSON.stringify({
                event: eventId,
                spielmodus: fight.spielmodus,
                map: fight.map,
                blueTeam: fight.blueTeam,
                redTeam: fight.redTeam,
                start: +fight.start,
                kampfleiter: fight.kampfleiter,
                group: fight.group
            })
        }).then(value => value.json())
            .then(EventFightSchema.parse)
    }

    public async updateFight(fightId: number, fight: UpdateFight): Promise<EventFight> {
        return await fetchWithToken(this.token, `/fights/${fightId}`, {
            method: "PUT",
            body: JSON.stringify({
                spielmodus: fight.spielmodus,
                map: fight.map,
                blueTeam: fight.blueTeam,
                redTeam: fight.redTeam,
                start: fight.start?.valueOf(),
                kampfleiter: fight.kampfleiter,
                group: fight.group
            })
        }).then(value => value.json())
            .then(EventFightSchema.parse)
    }

    public async deleteFight(fightId: number): Promise<void> {
        let res = await fetchWithToken(this.token, `/fights/${fightId}`, {
            method: "DELETE"
        })

        if (!res.ok) {
            throw new Error("Could not delete fight: " + res.statusText);
        }
    }
}
