import { z } from "zod";
import { ZColor, ZOverlay, ZPlacement } from "./common";
import { ZOverlayColor, ZOverlayOpacity } from "./overlay";
import { ZBaseStyling, ZLogo } from "./styling";

export const ZWorkspaceStyling = ZBaseStyling.extend({
  allowStyleOverwrite: z.boolean(),
});

export type TWorkspaceStyling = z.infer<typeof ZWorkspaceStyling>;

export const ZWorkspaceConfigIndustry = z.enum(["eCommerce", "saas", "other"]).nullable();
export type TWorkspaceConfigIndustry = z.infer<typeof ZWorkspaceConfigIndustry>;

export const ZWorkspaceConfigChannel = z.enum(["link", "app", "website"]).nullable();
export type TWorkspaceConfigChannel = z.infer<typeof ZWorkspaceConfigChannel>;

export const ZWorkspaceMode = z.enum(["surveys", "cx"]);
export type TWorkspaceMode = z.infer<typeof ZWorkspaceMode>;

export const ZWorkspaceConfig = z.object({
  channel: ZWorkspaceConfigChannel.optional(),
  industry: ZWorkspaceConfigIndustry.optional(),
  /**
   * The language new surveys in this workspace are authored in (ENG-2816). Unset/null means "whichever
   * language the person clicking New survey uses the app in".
   *
   * A canonical BCP-47 tag limited to the languages the survey runtime ships strings for. The allowed
   * set lives in `@formbricks/i18n-utils` and is enforced on write by `updateWorkspaceAction` — not
   * here, because `packages/types` deliberately depends on no other workspace package. Readers must
   * still treat an unsupported value as unset; `resolveDefaultSurveyLanguage` does.
   */
  defaultSurveyLanguage: z.string().trim().min(1).nullish(),
});

export type TWorkspaceConfig = z.infer<typeof ZWorkspaceConfig>;

export const ZLanguage = z.object({
  id: z.cuid2(),
  createdAt: z.date(),
  updatedAt: z.date(),
  code: z.string(),
  alias: z.string().nullable(),
  workspaceId: z.cuid2(),
});
export type TLanguage = z.infer<typeof ZLanguage>;

export const ZLanguageInput = z.object({
  code: z.string(),
  alias: z.string().nullable(),
});
export type TLanguageInput = z.infer<typeof ZLanguageInput>;

export const ZLanguageUpdate = z.object({
  alias: z.string().nullable(),
});
export type TLanguageUpdate = z.infer<typeof ZLanguageUpdate>;

export type TLogo = z.infer<typeof ZLogo>;

export const ZWorkspace = z.object({
  id: z.cuid2(),
  createdAt: z.date(),
  updatedAt: z.date(),
  legacyEnvironmentId: z.string().nullable().optional(),
  name: z.string().trim().min(1, {
    error: "Workspace name cannot be empty",
  }),
  organizationId: z.string(),
  styling: ZWorkspaceStyling,
  // This variable should be called `cooldownPeriod`, not `recontactDays`. It is related to the
  // Survey Cooldown Period feature (across surveys) and not the Recontact Options (per survey).
  recontactDays: z
    .int()
    .min(0, {
      error: "Must be a positive number",
    })
    .max(365, {
      error: "Must be less than 365",
    }),
  inAppSurveyBranding: z.boolean(),
  linkSurveyBranding: z.boolean(),
  config: ZWorkspaceConfig,
  placement: ZPlacement,
  clickOutsideClose: z.boolean(),
  overlay: ZOverlay,
  // Nullish so workspace objects built without them still type-check. null = the preset.
  overlayColor: ZOverlayColor.nullish(),
  overlayOpacity: ZOverlayOpacity.nullish(),
  languages: z.array(ZLanguage),
  appSetupCompleted: z.boolean(),
  logo: ZLogo.nullish(),
  customHeadScripts: z.string().nullish(),
  // ENG-2949: workspace custom CSS is deliberately NOT part of this type. The stored value (source,
  // compiled output and a previous revision) can be ~400 KB and must never ride along on the workspace
  // objects client components receive; read it through `getWorkspaceCustomCssRecord`
  // (`modules/custom-css/lib/service`), deliver it through `toDeliveredCustomCss`. It is never writable
  // through `ZWorkspaceUpdateInput` either.
});

export type TWorkspace = z.infer<typeof ZWorkspace>;

export const ZWorkspaceUpdateInput = z.object({
  name: z
    .string()
    .trim()
    .min(1, {
      error: "Workspace name cannot be empty",
    })
    .optional(),
  organizationId: z.string().optional(),
  highlightBorderColor: ZColor.nullish(),
  // This variable should be called `cooldownPeriod`, not `recontactDays`. It is related to the
  // Survey Cooldown Period feature (across surveys) and not the Recontact Options (per survey).
  recontactDays: z.int().optional(),
  inAppSurveyBranding: z.boolean().optional(),
  linkSurveyBranding: z.boolean().optional(),
  config: ZWorkspaceConfig.optional(),
  placement: ZPlacement.optional(),
  clickOutsideClose: z.boolean().optional(),
  overlay: ZOverlay.optional(),
  // null clears the custom value back to the preset.
  overlayColor: ZOverlayColor.nullish(),
  overlayOpacity: ZOverlayOpacity.nullish(),
  styling: ZWorkspaceStyling.optional(),
  logo: ZLogo.optional(),
  // Optimistic-concurrency baseline: the `updatedAt` the caller loaded. Only surfaces that edit a
  // composite field need it — `logo` carries both a url and a bgColor, so two saves from a stale
  // page can restore an url the other one just deleted the object for. Coerced because a server
  // action receives it as a string.
  expectedUpdatedAt: z.coerce.date().optional(),
  teamIds: z.array(z.string()).optional(),
  customHeadScripts: z.string().nullish(),
});

export type TWorkspaceUpdateInput = z.infer<typeof ZWorkspaceUpdateInput>;
