import { z } from 'zod';
import { BugApp, BugEnvironment, BugPriority, BugSeverity, BugStatus, BugType, Role } from '@prisma/client';

/**
 * A bug report's shape and limits (docs/bug-tracker-plan.md, BT2), in one
 * place. The web form mirrors these (hostelcare-frontend
 * src/features/bugs/bugChecks.ts); the server is what counts.
 */

export const BUG_LIMITS = {
  title: { min: 5, max: 160 },
  steps: { min: 10, max: 10_000 },
  result: { min: 3, max: 4_000 },
  appVersion: 40,
  device: 160,
  url: 500,
  comment: { min: 1, max: 10_000 },
  filesPerItem: 10,
  fileBytes: 10 * 1024 * 1024,
} as const;

export const TENANT_KINDS = ['ALL', 'HOSTEL', 'PG', 'DORMITORY', 'ENTERPRISE'] as const;
/** The role that hits the bug: anyone, or one of HostelCare's roles. */
export const AFFECTED_ROLES = [
  'ANY',
  Role.HOSTEL_ADMIN,
  Role.WARDEN,
  Role.MESS_ADMIN,
  Role.STUDENT,
  Role.GUARD,
  Role.GUARDIAN,
  Role.SUPER_ADMIN,
  Role.CRM_USER,
  Role.CONTENT_EDITOR,
] as const;

const noControl = (v: string) => !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(v);
const line = (label: string, min: number, max: number) =>
  z
    .string()
    .trim()
    .min(min, min > 1 ? `${label} must be at least ${min} characters` : `${label} is required`)
    .max(max, `${label} must be at most ${max} characters`)
    .refine((v) => noControl(v) && !/[\r\n]/.test(v), `${label} must be a single line`);
const block = (label: string, min: number, max: number) =>
  z
    .string()
    .max(max, `${label} must be at most ${max.toLocaleString('en-IN')} characters`)
    .refine(noControl, `${label} contains invalid characters`)
    .transform((v) => v.replace(/\r\n?/g, '\n').trim())
    .refine((v) => v.length >= min, min > 1 ? `${label} must be at least ${min} characters` : `${label} is required`);
/** Optional single line: empty or null clears it. */
const optionalLine = (label: string, max: number) =>
  z.union([z.string(), z.null()]).transform((v, ctx) => {
    const t = (v ?? '').trim();
    if (!t) return null;
    if (t.length > max) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} must be at most ${max} characters` });
    if (!noControl(t) || /[\r\n]/.test(t)) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} must be a single line` });
    return t;
  });
const optionalHttps = (label: string) =>
  optionalLine(label, BUG_LIMITS.url).refine((v) => v === null || /^https:\/\/[^\s]+$/i.test(v), `${label} must start with https://`);
/** A page address: any http(s) address, so a localhost page can be named too. */
const optionalUrl = (label: string) =>
  optionalLine(label, BUG_LIMITS.url).refine((v) => v === null || /^https?:\/\/[^\s]+$/i.test(v), `${label} must start with http:// or https://`);
const optionalBlock = (label: string, max: number) =>
  z.union([z.string(), z.null()]).transform((v, ctx) => {
    const t = (v ?? '').replace(/\r\n?/g, '\n').trim();
    if (!t) return null;
    if (t.length > max) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} must be at most ${max.toLocaleString('en-IN')} characters` });
    if (!noControl(t)) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} contains invalid characters` });
    return t;
  });

const ids = (max: number) => z.array(z.string().uuid()).max(max).transform((l) => [...new Set(l)]);

const fields = {
  type: z.nativeEnum(BugType),
  title: line('Title', BUG_LIMITS.title.min, BUG_LIMITS.title.max),
  steps: block('Steps to reproduce', BUG_LIMITS.steps.min, BUG_LIMITS.steps.max),
  expected: optionalBlock('Expected result', BUG_LIMITS.result.max),
  actual: optionalBlock('Actual result', BUG_LIMITS.result.max),
  app: z.nativeEnum(BugApp, { errorMap: () => ({ message: 'Choose the app' }) }),
  moduleId: z.string().uuid('Choose a module'),
  environment: z.nativeEnum(BugEnvironment),
  appVersion: optionalLine('App version', BUG_LIMITS.appVersion),
  /** BT5: the release it was found in; its name then fills `appVersion`. Null clears it. */
  foundInReleaseId: z.union([z.string().uuid('Choose a release'), z.null()]),
  device: optionalLine('Browser and device', BUG_LIMITS.device),
  pageUrl: optionalUrl('Page address'),
  videoUrl: optionalHttps('Video link'),
  tenantKind: z.enum(TENANT_KINDS),
  affectedRole: z.enum(AFFECTED_ROLES),
  severity: z.nativeEnum(BugSeverity, { errorMap: () => ({ message: 'Choose how bad it is' }) }),
  priority: z.union([z.nativeEnum(BugPriority), z.null()]),
};

/** A bug needs its expected and actual results; a suggestion does not. */
function resultsFor(v: { type?: BugType; expected?: string | null; actual?: string | null }, ctx: z.RefinementCtx) {
  if ((v.type ?? BugType.BUG) !== BugType.BUG) return;
  for (const [key, label] of [['expected', 'Expected result'], ['actual', 'Actual result']] as const) {
    if ((v[key] ?? '').length < BUG_LIMITS.result.min) ctx.addIssue({ code: z.ZodIssueCode.custom, path: [key], message: `${label} must be at least ${BUG_LIMITS.result.min} characters` });
  }
}

export const createBugSchema = z
  .object({
    ...fields,
    type: fields.type.default(BugType.BUG),
    environment: fields.environment.default(BugEnvironment.PRODUCTION),
    expected: fields.expected.optional(),
    actual: fields.actual.optional(),
    appVersion: fields.appVersion.optional(),
    foundInReleaseId: fields.foundInReleaseId.optional(),
    device: fields.device.optional(),
    pageUrl: fields.pageUrl.optional(),
    videoUrl: fields.videoUrl.optional(),
    tenantKind: fields.tenantKind.default('ALL'),
    affectedRole: fields.affectedRole.default('ANY'),
    priority: fields.priority.optional(),
    attachmentIds: ids(BUG_LIMITS.filesPerItem).default([]),
    /** BT6: the test run item this bug is the failure of; the two are linked. */
    testResultId: z.string().uuid().optional(),
  })
  .strict()
  .superRefine(resultsFor);
export type CreateBugInput = z.infer<typeof createBugSchema>;

/** An edit sends only what changed. */
export const updateBugSchema = z
  .object(fields)
  .partial()
  .strict()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');
export type UpdateBugInput = z.infer<typeof updateBugSchema>;

export const commentSchema = z
  .object({
    body: block('Comment', BUG_LIMITS.comment.min, BUG_LIMITS.comment.max),
    mentionIds: ids(20).default([]),
    attachmentIds: ids(BUG_LIMITS.filesPerItem).default([]),
  })
  .strict();
export const editCommentSchema = z.object({ body: block('Comment', BUG_LIMITS.comment.min, BUG_LIMITS.comment.max), mentionIds: ids(20).default([]) }).strict();

const csv = <T extends string>(values: readonly T[]) =>
  z
    .string()
    .optional()
    .transform((v) => (v ? v.split(',').map((x) => x.trim()).filter(Boolean) : []))
    .refine((l) => l.every((x) => (values as readonly string[]).includes(x)), 'Unknown filter value')
    .transform((l) => l as T[]);

export const SORTS = ['updated', 'newest', 'oldest', 'severity', 'priority'] as const;

export const listBugsSchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  limit: z.coerce.number().int().min(1).max(100).default(25),
  q: z.string().trim().max(100).optional().transform((v) => v || undefined),
  status: csv(Object.values(BugStatus)),
  severity: csv(Object.values(BugSeverity)),
  priority: csv([...Object.values(BugPriority), 'NONE'] as const),
  app: csv(Object.values(BugApp)),
  environment: csv(Object.values(BugEnvironment)),
  type: csv(Object.values(BugType)),
  tenantKind: csv(TENANT_KINDS),
  moduleId: z.string().uuid().optional(),
  /** A member's id, or "none" for unassigned. */
  assigneeId: z.union([z.string().uuid(), z.literal('none')]).optional(),
  reporterId: z.string().uuid().optional(),
  /** Reported more than this many days ago (the dashboard's "older than 7 / 30 days"). */
  olderThan: z.coerce.number().int().min(1).max(3650).optional(),
  /** BT5: bugs whose fix is in this release, or that were found in it. */
  fixedInReleaseId: z.string().uuid().optional(),
  foundInReleaseId: z.string().uuid().optional(),
  /** BT5, of bugs waiting for QA: "ready" can be tested now; "waiting" are in a release that isn't deployed yet. */
  deploy: z.enum(['ready', 'waiting']).optional(),
  sort: z.enum(SORTS).default('updated'),
});
export type ListBugsInput = z.infer<typeof listBugsSchema>;

/** "BUG-12", "bug 12", "#12" or "12" → 12. */
export function bugNumberFrom(text: string): number | null {
  const m = /^\s*(?:bug[\s-]*|#)?(\d{1,9})\s*$/i.exec(text);
  return m ? Number(m[1]) : null;
}

export const bugKey = (n: number) => `BUG-${n}`;

const STOP = new Set(['with', 'from', 'that', 'this', 'when', 'after', 'does', 'doesn', 'cannot', 'while', 'into', 'have', 'will', 'shows', 'show', 'showing', 'instead', 'should', 'page', 'screen', 'button', 'error', 'working', 'work', 'not']);
/** The words of a title worth matching on, for "looks like these". */
export function titleWords(title: string): string[] {
  return [...new Set(title.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 4 && !STOP.has(w)))].slice(0, 8);
}

// ── The fix-and-verify loop (BT3) ───────────────────────────────────────────

/**
 * What can be done to a bug, beyond editing it:
 *   start    a developer begins work                       → IN_PROGRESS
 *   ask      a developer needs more from the reporter       → NEEDS_INFO
 *   answer   the reporter or QA replies                     → OPEN
 *   fix      a developer says it is fixed                   → FIXED (waits for QA)
 *   suggest  a developer says it is not a fix: duplicate,
 *            not a bug, can't reproduce, won't fix          → FIXED with that reason (waits for QA)
 *   close    QA verifies the fix or agrees with the reason,
 *            or closes an open bug with a reason of its own → CLOSED
 *   reopen   QA: still broken, or closed wrongly             → REOPENED
 * A developer never closes: only QA or the super admin does (D5).
 */
export const BUG_ACTIONS = ['start', 'ask', 'answer', 'fix', 'suggest', 'close', 'reopen'] as const;
export type BugAction = (typeof BUG_ACTIONS)[number];

/** Reasons a bug is closed without a fix. VERIFIED is the fix being confirmed. */
export const CLOSE_REASONS = ['DUPLICATE', 'NOT_A_BUG', 'CANNOT_REPRODUCE', 'WONT_FIX'] as const;

const WORKABLE: BugStatus[] = [BugStatus.OPEN, BugStatus.IN_PROGRESS, BugStatus.REOPENED, BugStatus.NEEDS_INFO];

/** The actions this person may take on this bug now. The one place the rule lives. */
export function allowedActions(actor: { id: string; role: Role }, bug: { status: BugStatus; reporterId: string }): BugAction[] {
  const dev = actor.role === Role.DEVELOPER || actor.role === Role.SUPER_ADMIN;
  const qa = actor.role === Role.QA || actor.role === Role.SUPER_ADMIN;
  const out: BugAction[] = [];
  const s = bug.status;
  if (dev && WORKABLE.includes(s)) {
    if (s !== BugStatus.IN_PROGRESS) out.push('start');
    if (s !== BugStatus.NEEDS_INFO) out.push('ask');
    out.push('fix', 'suggest');
  }
  // The question is for whoever reported it; any tester (or the super admin) can answer too.
  if (s === BugStatus.NEEDS_INFO && (qa || bug.reporterId === actor.id)) out.push('answer');
  if (qa && s !== BugStatus.CLOSED) out.push('close');
  if (qa && (s === BugStatus.FIXED || s === BugStatus.CLOSED)) out.push('reopen');
  return out;
}

const note = (label: string, min = 5) => block(label, min, 4_000);
const optionalNote = optionalBlock('Note', 4_000);
const bugRef = z.union([z.number().int().positive(), z.string().trim().max(20)]).transform((v, ctx) => {
  const n = typeof v === 'number' ? v : bugNumberFrom(v);
  if (n === null) {
    ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Enter a bug number, like BUG-12' });
    return z.NEVER;
  }
  return n;
});

export const moveSchema = z.discriminatedUnion('action', [
  z.object({ action: z.literal('start') }).strict(),
  z.object({ action: z.literal('ask'), note: note('Your question') }).strict(),
  z.object({ action: z.literal('answer'), note: note('Your answer') }).strict(),
  z
    .object({
      action: z.literal('fix'),
      note: note('What was wrong and what you changed'),
      fixLink: optionalHttps('Commit or pull request link').optional(),
      fixedIn: optionalLine('Fixed in', 60).optional(),
      /** BT5: a release from the list, instead of typing `fixedIn`. */
      fixedInReleaseId: z.union([z.string().uuid('Choose a release'), z.null()]).optional(),
    })
    .strict(),
  z.object({ action: z.literal('suggest'), resolution: z.enum(CLOSE_REASONS), note: note('Why'), duplicateOf: bugRef.optional() }).strict(),
  z.object({ action: z.literal('close'), resolution: z.enum(CLOSE_REASONS).optional(), note: optionalNote.optional(), duplicateOf: bugRef.optional() }).strict(),
  z.object({ action: z.literal('reopen'), note: note('Why it is reopened') }).strict(),
]);
export type MoveInput = z.infer<typeof moveSchema>;

export const assignSchema = z.object({ assigneeId: z.union([z.string().uuid('Choose a developer'), z.null()]) }).strict();

export const bulkSchema = z.discriminatedUnion('action', [
  z.object({ action: z.literal('assign'), numbers: z.array(z.number().int().positive()).min(1).max(50), assigneeId: z.union([z.string().uuid(), z.null()]) }).strict(),
  z.object({ action: z.literal('priority'), numbers: z.array(z.number().int().positive()).min(1).max(50), priority: z.union([z.nativeEnum(BugPriority), z.null()]) }).strict(),
  z.object({ action: z.literal('duplicate'), numbers: z.array(z.number().int().positive()).min(1).max(50), duplicateOf: bugRef }).strict(),
]);
export type BulkInput = z.infer<typeof bulkSchema>;
