import { type ActionFunction, redirect } from "react-router";
import { requireUser } from "~/features/auth/core/user.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import {
	HIGHLIGHT_CHECKBOX_NAME,
	HIGHLIGHT_TOURNAMENT_CHECKBOX_NAME,
} from "~/features/user-page/user-page-constants";
import { normalizeFormFieldArray } from "~/utils/arrays";
import { parseRequestPayload } from "~/utils/remix.server";
import { userResultsPage } from "~/utils/urls";
import { editHighlightsActionSchema } from "../user-page-schemas";

export const action: ActionFunction = async ({ request }) => {
	const user = requireUser();
	const data = await parseRequestPayload({
		request,
		schema: editHighlightsActionSchema,
	});

	const resultTeamIds = normalizeFormFieldArray(
		data[HIGHLIGHT_CHECKBOX_NAME],
	).map((id) => Number.parseInt(id, 10));
	const resultTournamentTeamIds = normalizeFormFieldArray(
		data[HIGHLIGHT_TOURNAMENT_CHECKBOX_NAME],
	).map((id) => Number.parseInt(id, 10));

	await UserRepository.updateOwnResultHighlights({
		resultTeamIds,
		resultTournamentTeamIds,
	});

	throw redirect(userResultsPage(user));
};
