import type { Flair } from './FlairStore.svelte';
import { post } from './utils';

export const ApplicationStatus = Object.freeze({
	ToApply: 0,
	WorkingOnIt: 1,
	Ignore: 2,
	ApplyedButSaidNo: 3,
	Applyed: 4,
	Expired: 5
});

export const ApplicationStatusMaping: Record<
	(typeof ApplicationStatus)[keyof typeof ApplicationStatus],
	string
> = Object.freeze({
	0: 'To Apply',
	1: 'Working On It',
	2: 'Ignore',
	3: 'Applyed But Said No',
	4: 'Applyed',
	5: 'Expired'
});

export type View = {
    id: string,
    application_id: string,
    time: string,
}

export type Application = {
	id: string;
	url: string;
	original_url: string | null;
	unique_url: string | null;
	title: string;
	user_id: string;
	extra_data: string;
	payrange: string;
	status: number;
    recruiter: string;
    company: string;
    message: string;
    linked_application: string;
	flairs: Flair[];
    views: View[];
};

function createApplicationStore() {
	let applications: Application[] = $state([]);
	let applyed: Application[] = $state([]);

	let dragApplication: Application | undefined = $state(undefined);

	return {
		/**
		 * @throws {Error}
		 */
		async loadApplications(force = false) {
			if (!force && applications.length > 1) {
				return;
			}
			applications = await post('application/list', { status: 0 });
		},

		/**
		 * @throws {Error}
		 */
		async loadAplyed(force = false) {
			if (!force && applications.length > 1) {
				return;
			}
			applyed = await post('application/list', { status: ApplicationStatus.Applyed });
		},

		clear() {
			applications = [];
		},

		dragStart(application: Application) {
			dragApplication = application;
		},

		dragEnd() {
			dragApplication = undefined;
		},

		get dragging() {
			return dragApplication;
		},

		get applications() {
			return applications;
		},

		get applyed() {
			return applyed;
		}
	};
}

export const applicationStore = createApplicationStore();
