import { inject } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivateFn,
  RouterStateSnapshot,
} from '@angular/router';
import { ApplicationService } from '@core/application';
import { Config } from '@core/config';
import { take } from 'rxjs/operators';
import z from 'zod';

export const ActivateProcessIdGuard: CanActivateFn = async (
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot,
) => {
  const application = inject(ApplicationService);

  const processIdStr = route.params.processId;

  if (!processIdStr) {
    return false;
  }

  const processId = Number(processIdStr);

  // Check if Process already exists
  const process = await application
    .getProcessById$(processId)
    .pipe(take(1))
    .toPromise();

  if (!process) {
    application.createProcess({
      id: processId,
      type: 'cart',
      section: 'customer',
      name: `Vorgang ${processId}`,
    });
  }

  application.activateProcess(processId);

  return true;
};

export const ActivateProcessIdWithConfigKeyGuard: (
  key: string,
) => CanActivateFn =
  (key) =>
  async (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
    const application = inject(ApplicationService);
    const config = inject(Config);

    const processId = config.get(`process.ids.${key}`, z.coerce.number());

    if (typeof processId !== 'number' || isNaN(processId)) {
      return false;
    }

    const processTitle = config.get(
      `process.titles.${key}`,
      z.string().default(key),
    );

    const process = await application
      .getProcessById$(processId)
      .pipe(take(1))
      .toPromise();

    if (!process) {
      await application.createProcess({
        id: processId,
        type: key,
        section: 'customer', // Not important anymore
        name: processTitle,
      });
    }

    application.activateProcess(processId);

    return true;
  };
