//
// POST /Users/AuthenticateByName  →  { AccessToken, User: { Id, Name } }
//
// Async via http_submit; on_login_response runs on the main thread.
//

Login_User :: struct {
    Id:   string;
    Name: string;
}

Login_Response :: struct {
    AccessToken: string;
    User:        Login_User;
}

jellyfin_login_async :: (c: *Jellyfin_Client) {
    if c.login_pending  return;
    c.login_pending = true;
    body := tprint("{\"Username\":\"%\",\"Pw\":\"%\"}", c.username, c.password);
    log_info("auth: logging in as %", c.username);
    http_submit("POST", "/Users/AuthenticateByName", body, on_done=on_login_response);
}

jellyfin_logout :: (c: *Jellyfin_Client) {
    free(c.auth_token);
    free(c.user_id);
    c.auth_token = "";
    c.user_id    = "";
    c.logged_in  = false;
    config_clear();
}

#scope_file

on_login_response :: (task: *Http_Task) {
    app.jellyfin.login_pending = false;
    if !task.response.ok {
        log_error("login failed: status=% body=%", task.response.status_code, slice(task.response.body, 0, min(300, task.response.body.count)));
        return;
    }

    ok, parsed := Jaison.json_parse_string(task.response.body, Login_Response);
    if !ok {
        log_error("login: failed to parse JSON");
        return;
    }

    app.jellyfin.auth_token = copy_string(parsed.AccessToken);
    app.jellyfin.user_id    = copy_string(parsed.User.Id);
    app.jellyfin.logged_in  = true;
    log_info("auth: logged in as % (id=%)", parsed.User.Name, app.jellyfin.user_id);

    config_save();
    app.current_view = .LIBRARY;
    library_refresh_artists();
}
