'use server';

import { getConnection } from '@alga-psa/db';
import { SupportedLocale, isSupportedLocale, LOCALE_CONFIG } from '@alga-psa/core/i18n/config';
import { withOptionalAuth, type AuthContext } from '@alga-psa/auth';
import type { IUserWithRoles } from '@alga-psa/types';

/**
 * Get the user's client ID from their contact
 */
async function getUserClientId(userId: string, tenantId: string): Promise<string | null> {
  const knex = await getConnection(tenantId);

  // Get user's contact_id
  const user = await knex('users')
    .where({
      user_id: userId,
      tenant: tenantId
    })
    .first();

  if (!user?.contact_id) return null;

  // Get contact's client
  const contact = await knex('contacts')
    .where({
      contact_name_id: user.contact_id,
      tenant: tenantId
    })
    .first();

  return contact?.client_id || null;
}

/**
 * Get what locale would be inherited if the user had no personal preference
 * This checks client -> tenant -> system default
 */
export const getInheritedLocaleAction = withOptionalAuth(async (user: IUserWithRoles | null, ctx: AuthContext | null): Promise<{
  locale: SupportedLocale;
  source: 'client' | 'tenant' | 'system';
}> => {
  if (!user || !ctx) {
    return {
      locale: LOCALE_CONFIG.defaultLocale as SupportedLocale,
      source: 'system'
    };
  }

  const { tenant } = ctx;
  const knex = await getConnection(tenant);

  // 1. Check client preference
  let clientId: string | null = null;

  // For client users, get their client
  if (user.user_type === 'client') {
    clientId = await getUserClientId(user.user_id, tenant);
  }

  if (clientId) {
    const client = await knex('clients')
      .where({
        client_id: clientId,
        tenant
      })
      .first();

    const clientLocale = client?.properties?.defaultLocale;
    if (clientLocale && isSupportedLocale(clientLocale)) {
      return {
        locale: clientLocale,
        source: 'client'
      };
    }
  }

  const tenantSettings = await knex('tenant_settings')
    .where({ tenant })
    .first();

  // 2. Client-portal default — applies to client-portal users only
  if (user.user_type === 'client') {
    const clientPortalLocale = tenantSettings?.settings?.clientPortal?.defaultLocale;
    if (clientPortalLocale && isSupportedLocale(clientPortalLocale)) {
      return {
        locale: clientPortalLocale,
        source: 'tenant'
      };
    }
  }

  // 3. Organization default (applies to everyone)
  const tenantDefaultLocale = tenantSettings?.settings?.defaultLocale;
  if (tenantDefaultLocale && isSupportedLocale(tenantDefaultLocale)) {
    return {
      locale: tenantDefaultLocale,
      source: 'tenant'
    };
  }

  // Legacy MSP-only default written by the retired split UI
  if (user.user_type === 'internal') {
    const legacyMspLocale = tenantSettings?.settings?.mspPortal?.defaultLocale;
    if (legacyMspLocale && isSupportedLocale(legacyMspLocale)) {
      return {
        locale: legacyMspLocale,
        source: 'tenant'
      };
    }
  }

  // 4. System default
  return {
    locale: LOCALE_CONFIG.defaultLocale as SupportedLocale,
    source: 'system'
  };
});
