import { z } from 'zod';

export const ReviewStatusSchema = z.enum([
  'pending',
  'assigned',
  'approved',
  'rejected',
  'cancelled',
  'expired',
]);
export const ReviewPrioritySchema = z.enum(['low', 'normal', 'high', 'urgent']);
export const ReviewScopeSchema = z.enum(['org', 'workspace']);

export const ReviewItemSchema = z.object({
  id: z.string().min(1),
  productId: z.string().min(1),
  title: z.string().min(1),
  description: z.string().min(1),
  category: z.string().min(1),
  status: ReviewStatusSchema,
  priority: ReviewPrioritySchema,
  scope: ReviewScopeSchema,
  orgId: z.string().min(1),
  workspaceId: z.string().optional(),
  requestedBy: z.string().min(1),
  assignedTo: z.string().optional(),
  runId: z.string().optional(),
  source: z.string().min(1),
  actionType: z.string().min(1),
  metadata: z.record(z.unknown()).optional(),
  resolution: z
    .object({
      decision: z.enum(['approved', 'rejected', 'cancelled', 'expired']),
      reason: z.string().optional(),
      actedBy: z.string().optional(),
      actedAt: z.string(),
    })
    .optional(),
  dueAt: z.string().optional(),
  createdAt: z.string(),
  updatedAt: z.string(),
});

export type ReviewItemDoc = z.infer<typeof ReviewItemSchema> & {
  _ts?: number;
  _etag?: string;
};

export const CreateReviewSchema = z.object({
  title: z.string().min(1),
  description: z.string().min(1),
  category: z.string().min(1),
  priority: ReviewPrioritySchema.default('normal'),
  scope: ReviewScopeSchema.default('org'),
  orgId: z.string().min(1),
  workspaceId: z.string().optional(),
  assignedTo: z.string().optional(),
  runId: z.string().optional(),
  source: z.string().min(1),
  actionType: z.string().min(1),
  metadata: z.record(z.unknown()).optional(),
  dueAt: z.string().optional(),
});

export const UpdateReviewSchema = z.object({
  status: ReviewStatusSchema.optional(),
  priority: ReviewPrioritySchema.optional(),
  assignedTo: z.string().optional(),
  dueAt: z.string().optional(),
  metadata: z.record(z.unknown()).optional(),
});

export const ReviewDecisionSchema = z.object({
  decision: z.enum(['approved', 'rejected', 'cancelled']),
  reason: z.string().optional(),
});

export const ListReviewsQuerySchema = z.object({
  status: ReviewStatusSchema.optional(),
  priority: ReviewPrioritySchema.optional(),
  scope: ReviewScopeSchema.optional(),
  orgId: z.string().optional(),
  workspaceId: z.string().optional(),
  assignedTo: z.string().optional(),
  runId: z.string().optional(),
  limit: z.coerce.number().min(1).max(100).default(20),
});

export type ListReviewsQuery = z.infer<typeof ListReviewsQuerySchema>;
