import { z } from "zod";
import { invoiceSchema } from "../billing/schema";

export const activityTypeSchema = z.enum([
  "invoice_created",
  "invoice_paid",
  "service_activated",
  "case_created",
  "case_closed",
]);

export const activitySchema = z.object({
  id: z.string(),
  type: activityTypeSchema,
  title: z.string(),
  description: z.string().optional(),
  date: z.string(),
  relatedId: z.number().optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
});

export const invoiceActivityMetadataSchema = z
  .object({
    amount: z.number(),
    currency: z.string().optional(),
    dueDate: z.string().optional(),
    invoiceNumber: z.string().optional(),
    status: z.string().optional(),
  })
  .partial()
  .refine(data => typeof data.amount === "number", {
    message: "amount is required",
    path: ["amount"],
  });

export const serviceActivityMetadataSchema = z
  .object({
    productName: z.string().optional(),
    registrationDate: z.string().optional(),
    status: z.string().optional(),
  })
  .partial();

export const dashboardStatsSchema = z.object({
  activeSubscriptions: z.number().int().nonnegative(),
  unpaidInvoices: z.number().int().nonnegative(),
  openCases: z.number().int().nonnegative(),
  recentOrders: z.number().int().nonnegative().optional(),
  totalSpent: z.number().nonnegative().optional(),
  currency: z.string(),
});

export const nextInvoiceSchema = z.object({
  id: z.number().int().positive(),
  dueDate: z.string(),
  amount: z.number(),
  currency: z.string(),
});

export const dashboardSummarySchema = z.object({
  stats: dashboardStatsSchema,
  nextInvoice: nextInvoiceSchema.nullable(),
  recentActivity: z.array(activitySchema),
});

export const dashboardErrorSchema = z.object({
  code: z.string(),
  message: z.string(),
  details: z.record(z.string(), z.unknown()).optional(),
});

export const activityFilterSchema = z.enum(["all", "billing", "orders", "support"]);

export const activityFilterConfigSchema = z.object({
  key: activityFilterSchema,
  label: z.string(),
  types: z.array(activityTypeSchema).optional(),
});

export const dashboardSummaryResponseSchema = dashboardSummarySchema.extend({
  invoices: z.array(invoiceSchema).optional(),
});

export type InvoiceActivityMetadata = z.infer<typeof invoiceActivityMetadataSchema>;
export type ServiceActivityMetadata = z.infer<typeof serviceActivityMetadataSchema>;
