/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

import { readable, writable } from "svelte/store";
import { ResponseUserSchema } from "@components/types/data";

export class AuthV2Repo {
    constructor() {
        this.request("/data/me").then((value) => {
            if (value.ok) {
                loggedIn.set(true);
            } else {
                loggedIn.set(false);
            }
        });
    }

    async login(name: string, password: string) {
        try {
            await this.request("/auth", {
                method: "POST",
                body: JSON.stringify({
                    name,
                    password,
                    keepLoggedIn: true,
                }),
            })
                .then((value) => value.json())
                .then((value) => ResponseUserSchema.parse(value));

            loggedIn.set(true);

            return true;
        } catch (e) {
            return false;
        }
    }

    async loginDiscord(token: string) {
        try {
            await this.request("/auth/discord", {
                method: "POST",
                body: token,
                headers: {
                    "Content-Type": "text/plain",
                },
            })
                .then((value) => value.json())
                .then((value) => ResponseUserSchema.parse(value));
            loggedIn.set(true);
            return true;
        } catch (e) {
            return false;
        }
    }

    async logout() {
        await this.request("/auth", {
            method: "DELETE",
        });
        loggedIn.set(false);
    }

    async request(url: string, params: RequestInit = {}) {
        return fetch(`${import.meta.env.PUBLIC_API_SERVER}${url}`, {
            ...params,
            credentials: "include",
            headers: {
                "Content-Type": "application/json",
                ...params.headers,
            },
        });
    }
}

export const loggedIn = writable<boolean | undefined>(undefined);

export const authV2Repo = readable(new AuthV2Repo());
