import { fail } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';
import { getUserCompanies } from '$lib/server/api';
import { createWorkspaceInvite } from '$lib/server/workspace-provision';
import { WORKSPACE_INVITE_ROLES } from '$lib/server/workspace-provision.shared';

export const load: PageServerLoad = async ({ cookies, fetch }) => {
	// La organización destino sale de las compañías del usuario (mismo origen que
	// el switcher, vía /v1/auth/my-companies). Así no se escribe el slug a mano ni
	// se depende de listar todos los tenants del Hub con un token KC que caduca.
	const companiesRaw = await getUserCompanies(cookies, fetch);
	const companies = (companiesRaw ?? [])
		.filter((c) => c && c.tenant_slug)
		.map((c) => ({
			id: c.id as number,
			name: c.name as string,
			tenant_slug: c.tenant_slug as string,
			tenant_name: (c.tenant_name as string) || (c.tenant_slug as string)
		}));

	return { companies, roles: WORKSPACE_INVITE_ROLES };
};

export const actions: Actions = {
	invite: async ({ request, cookies, fetch }) => {
		const accessToken = getKcAccessToken(cookies);
		if (!accessToken) return fail(401, { error: 'Tu sesión expiró. Vuelve a entrar al CRM.' });

		const data = await request.formData();
		const email = String(data.get('email') ?? '').trim();
		const tenant_slug = String(data.get('tenant_slug') ?? '')
			.trim()
			.toLowerCase();
		const role = String(data.get('role') ?? 'user').trim();

		const values = { email, tenant_slug, role };

		if (!email || !email.includes('@')) {
			return fail(422, { error: 'Ingresa un email válido para invitar.', values });
		}
		if (!tenant_slug) {
			return fail(422, { error: 'Selecciona la compañía destino.', values });
		}
		if (!WORKSPACE_INVITE_ROLES.includes(role as (typeof WORKSPACE_INVITE_ROLES)[number])) {
			return fail(422, { error: 'Rol inválido.', values });
		}

		const res = await createWorkspaceInvite(accessToken, fetch, { email, tenant_slug, role });
		if (!res.ok) {
			return fail(res.forbidden ? 403 : 422, { error: res.error, values });
		}

		return {
			success: true,
			email: res.data.email,
			inviteUrl: res.data.invite_url,
			expiresAt: res.data.expires_at
		};
	}
};
