import { mutation } from "../_generated/server";
import { v } from "convex/values";

/**
 * Create a new support ticket
 * Phase 3: Notifications & Support
 */
export const createTicket = mutation({
  args: {
    userId: v.string(),
    subject: v.string(),
    message: v.string(),
    category: v.string(),
    priority: v.optional(v.string()),
    attachments: v.optional(v.any()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    const id = await ctx.db.insert("support_tickets", {
      userId: args.userId,
      subject: args.subject,
      message: args.message,
      category: args.category as
        | "BILLING"
        | "TECHNICAL"
        | "FEATURE_REQUEST"
        | "OTHER",
      priority: (args.priority as "LOW" | "NORMAL" | "URGENT") ?? "NORMAL",
      status: "OPEN",
      attachments: args.attachments,
      createdAt: now,
      updatedAt: now,
    });

    // Create the initial message atomically with the ticket
    await ctx.db.insert("ticket_messages", {
      ticketId: id,
      senderId: args.userId,
      senderType: "USER" as const,
      message: args.message,
      attachments: args.attachments,
      isRead: false,
      createdAt: now,
    });

    return id;
  },
});

/**
 * Update a support ticket's fields
 * Phase 3: Notifications & Support
 */
export const updateTicket = mutation({
  args: {
    id: v.id("support_tickets"),
    subject: v.optional(v.string()),
    message: v.optional(v.string()),
    category: v.optional(v.string()),
    priority: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const { id, ...updates } = args;
    const filtered: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(updates)) {
      if (value !== undefined) {
        filtered[key] = value;
      }
    }
    filtered.updatedAt = Date.now();
    await ctx.db.patch(id, filtered);
  },
});

/**
 * Add a message to a support ticket
 * Phase 3: Notifications & Support
 */
export const addMessage = mutation({
  args: {
    ticketId: v.string(),
    senderId: v.string(),
    senderType: v.string(),
    message: v.string(),
    attachments: v.optional(v.any()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    const id = await ctx.db.insert("ticket_messages", {
      ticketId: args.ticketId,
      senderId: args.senderId,
      senderType: args.senderType as "USER" | "STAFF",
      message: args.message,
      attachments: args.attachments,
      isRead: false,
      createdAt: now,
    });
    return id;
  },
});

/**
 * Update support ticket status
 * Phase 3: Notifications & Support
 */
export const updateStatus = mutation({
  args: {
    id: v.id("support_tickets"),
    status: v.string(),
    resolvedBy: v.optional(v.string()),
    resolution: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    const patch: Record<string, unknown> = {
      status: args.status,
      updatedAt: now,
    };
    if (args.status === "RESOLVED" || args.status === "CLOSED") {
      patch.resolvedAt = now;
      if (args.resolvedBy) patch.resolvedBy = args.resolvedBy;
      if (args.resolution) patch.resolution = args.resolution;
    }
    await ctx.db.patch(args.id, patch);
  },
});

/**
 * Close a support ticket
 * Phase 3: Notifications & Support
 */
export const closeTicket = mutation({
  args: {
    id: v.id("support_tickets"),
    resolvedBy: v.optional(v.string()),
    resolution: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    await ctx.db.patch(args.id, {
      status: "CLOSED",
      resolvedAt: now,
      resolvedBy: args.resolvedBy,
      resolution: args.resolution,
      updatedAt: now,
    });
  },
});

/**
 * Update a contact submission's fields
 * Group G: Contact Form Migration
 */
export const updateContactSubmission = mutation({
  args: {
    id: v.id("contact_submissions"),
    status: v.optional(v.string()),
    notes: v.optional(v.string()),
    resolved_at: v.optional(v.number()),
    resolved_by: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const { id, ...updates } = args;
    const filtered: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(updates)) {
      if (value !== undefined) {
        filtered[key] = value;
      }
    }
    filtered.updated_at = Date.now();
    await ctx.db.patch(id, filtered);
    return id;
  },
});

/**
 * Delete a contact submission
 * Group G: Contact Form Migration
 */
export const deleteContactSubmission = mutation({
  args: { id: v.id("contact_submissions") },
  handler: async (ctx, args) => {
    await ctx.db.delete(args.id);
  },
});

/**
 * Create a new contact form submission
 * Group G: Contact Form Migration
 */
export const createContactSubmission = mutation({
  args: {
    name: v.string(),
    email: v.string(),
    phone: v.string(),
    company: v.optional(v.string()),
    topic: v.string(),
    message: v.string(),
    preferred_language: v.string(),
    consent: v.boolean(),
    ip_address: v.optional(v.string()),
    user_agent: v.optional(v.string()),
    submission_language: v.optional(v.string()),
    attachments: v.optional(v.any()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    const id = await ctx.db.insert("contact_submissions", {
      name: args.name,
      email: args.email,
      phone: args.phone,
      company: args.company,
      topic: args.topic,
      message: args.message,
      preferred_language: args.preferred_language,
      consent: args.consent,
      ip_address: args.ip_address,
      user_agent: args.user_agent,
      submission_language: args.submission_language,
      attachments: args.attachments ?? null,
      status: "NEW",
      created_at: now,
      updated_at: now,
    });
    return id;
  },
});
