import type { CampaignGroupRepository } from "@/internal/repository/campaigns/campaign_groups";
import type { CampaignRepository } from "@/internal/repository/campaigns/campaigns";
import type { CampaignTagRepository } from "@/internal/repository/campaigns/campaign_tags";
import { emitCampaignStatus } from "@/internal/socket";
import { logError } from "@/lib/logger";
import type { CampaignService } from "./campaign.service";

export class CampaignGroupError extends Error {
  constructor(message: string, public status: 400 | 404 | 409 = 400) {
    super(message);
  }
}

/**
 * Parent campaign lifecycle, derived from its subcampaigns:
 *  PAUSED    — parent paused by a user (stored flag wins over everything)
 *  DRAFT     — no subcampaigns, or none scheduled/started yet
 *  SCHEDULED — at least one subcampaign scheduled, none started
 *  SENDING   — a subcampaign is queued or sending right now
 *  ACTIVE    — some subcampaigns sent, others still pending
 *  COMPLETED — every subcampaign is SENT/COMPLETED
 */
export type CampaignGroupStatus = "PAUSED" | "DRAFT" | "SCHEDULED" | "SENDING" | "ACTIVE" | "COMPLETED";

const DONE = new Set(["SENT", "COMPLETED"]);
const IN_FLIGHT = new Set(["QUEUED", "SENDING"]);
const MAX_DRAFTS = 50;

export type CampaignDraft = {
  name?: string;
  title?: string;
  body?: string;
  image_url?: string | null;
  target_criteria: Record<string, unknown>;
  additional_data?: Record<string, unknown>;
  scheduled_at?: string | null;
  sendNow?: boolean;
};

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

type Child = {
  id: string;
  status: string;
  scheduled_at: Date | string | null;
  created_at: Date | string;
  updated_at: Date | string | null;
  sent_count: number | null;
  total_count: number | null;
  click_count: number | null;
  open_count: number | null;
};

const toTime = (v: Date | string | null | undefined) => (v ? new Date(v).getTime() : null);

export function deriveGroupStatus(groupStatus: string, children: Child[]): CampaignGroupStatus {
  if (groupStatus === "PAUSED") return "PAUSED";
  if (children.length === 0) return "DRAFT";
  if (children.some((c) => IN_FLIGHT.has(c.status))) return "SENDING";
  if (children.every((c) => DONE.has(c.status))) return "COMPLETED";
  // FAILED/STOPPED with sends already out still count as "started".
  if (children.some((c) => DONE.has(c.status) || Number(c.sent_count || 0) > 0)) return "ACTIVE";
  if (children.some((c) => c.status === "SCHEDULED")) return "SCHEDULED";
  return "DRAFT";
}

export function summarizeGroup(group: { status: string }, children: Child[]) {
  const now = Date.now();
  const status = deriveGroupStatus(group.status, children);

  // Start = earliest send moment: scheduled time, or creation time for send-now campaigns.
  const starts = children
    .filter((c) => c.status !== "DRAFT")
    .map((c) => toTime(c.scheduled_at) ?? toTime(c.created_at))
    .filter((t): t is number => t !== null);

  const upcoming = children
    .filter((c) => c.status === "SCHEDULED" || (c.status === "STOPPED" && Number(c.sent_count || 0) === 0))
    .map((c) => ({ id: c.id, at: toTime(c.scheduled_at) }))
    .filter((u): u is { id: string; at: number } => u.at !== null && u.at >= now)
    .sort((a, b) => a.at - b.at);

  const sending = children.find((c) => IN_FLIGHT.has(c.status));
  const sum = (key: keyof Child) => children.reduce((acc, c) => acc + Number(c[key] || 0), 0);

  return {
    status,
    start_at: starts.length ? new Date(Math.min(...starts)).toISOString() : null,
    next_scheduled_at: upcoming[0] ? new Date(upcoming[0].at).toISOString() : null,
    next_campaign_id: upcoming[0]?.id ?? null,
    current_campaign_id: sending?.id ?? null,
    progress: {
      total: children.length,
      completed: children.filter((c) => DONE.has(c.status)).length,
      active: children.filter((c) => IN_FLIGHT.has(c.status)).length,
      upcoming: children.filter((c) => ["DRAFT", "SCHEDULED", "STOPPED"].includes(c.status) && Number(c.sent_count || 0) === 0).length,
      failed: children.filter((c) => c.status === "FAILED" || (c.status === "STOPPED" && Number(c.sent_count || 0) > 0)).length,
    },
    totals: {
      sent: sum("sent_count"),
      audience: sum("total_count"),
      clicks: sum("click_count"),
      opens: sum("open_count"),
    },
  };
}

function normalizeTagName(rawName: unknown): string {
  const name = typeof rawName === "string" ? rawName.trim().replace(/\s+/g, " ") : "";
  if (!name) throw new CampaignGroupError("Tag name is required");
  if (name.length > 60) throw new CampaignGroupError("Tag name must be 60 characters or fewer");
  return name;
}

export type CampaignGroupListFilters = {
  search?: string;
  status?: string;
  tags?: string;
  createdFrom?: string;
  createdTo?: string;
  createdBy?: string;
  scheduledFrom?: string;
  scheduledTo?: string;
  pendingOnly?: boolean;
};

type Window = { from: number; to: number };

const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;

function dayWindow(from?: string, to?: string): Window | null {
  const validFrom = from && DAY_RE.test(from) ? new Date(`${from}T00:00:00`).getTime() : null;
  const validTo = to && DAY_RE.test(to) ? new Date(`${to}T23:59:59.999`).getTime() : null;
  if (validFrom === null && validTo === null) return null;
  return { from: validFrom ?? -Infinity, to: validTo ?? Infinity };
}

function inWindow(value: Date | string, window: Window): boolean {
  const time = new Date(value).getTime();
  return time >= window.from && time <= window.to;
}

export class CampaignGroupService {
  constructor(
    private groupRepo: CampaignGroupRepository,
    private campaignRepo: CampaignRepository,
    private campaignService: CampaignService,
    private tagRepo: CampaignTagRepository,
  ) {}

  async listTags() {
    return this.tagRepo.list();
  }

  async listTagsWithUsage() {
    return this.tagRepo.listWithUsage();
  }

  async createTag(rawName: unknown, createdBy?: string) {
    const name = normalizeTagName(rawName);
    const existing = await this.tagRepo.findByName(name);
    return existing ?? this.tagRepo.create(name, createdBy ?? null);
  }

  async renameTag(id: string, rawName: unknown) {
    await this.requireTag(id);
    const name = normalizeTagName(rawName);
    const clash = await this.tagRepo.findByName(name);
    if (clash && clash.id !== id) throw new CampaignGroupError(`A tag named "${clash.name}" already exists`, 409);
    return this.tagRepo.rename(id, name);
  }

  async deleteTag(id: string) {
    await this.requireTag(id);
    await this.tagRepo.delete(id);
    return { deleted: id };
  }

  private async requireTag(id: string) {
    if (!UUID_RE.test(id)) throw new CampaignGroupError("Tag not found", 404);
    const tag = await this.tagRepo.getById(id);
    if (!tag) throw new CampaignGroupError("Tag not found", 404);
    return tag;
  }

  private async validTagIds(tagIds: unknown): Promise<string[]> {
    if (!Array.isArray(tagIds)) return [];
    const ids = [...new Set(tagIds.filter((t): t is string => typeof t === "string" && UUID_RE.test(t)))];
    const existing = await this.tagRepo.existingIds(ids);
    if (existing.length !== ids.length) throw new CampaignGroupError("One or more tags no longer exist");
    return ids;
  }

  private async requireGroup(id: string) {
    if (!UUID_RE.test(id)) throw new CampaignGroupError("Parent campaign not found", 404);
    const group = await this.groupRepo.getById(id);
    if (!group) throw new CampaignGroupError("Parent campaign not found", 404);
    return group;
  }

  private async load(id: string) {
    const group = await this.requireGroup(id);
    const children = await this.groupRepo.getChildren([id]);
    return { group, children, summary: summarizeGroup(group, children) };
  }

  async list(filters: CampaignGroupListFilters = {}) {
    const groups = await this.groupRepo.list({ search: filters.search });
    const tagsByGroup = await this.tagRepo.forGroups(groups.map((g) => g.id));
    const children = await this.groupRepo.getChildren(groups.map((g) => g.id));
    const byGroup = new Map<string, typeof children>();
    for (const c of children) {
      const list = byGroup.get(c.parent_id!) ?? [];
      list.push(c);
      byGroup.set(c.parent_id!, list);
    }
    const items = groups.map((g) => ({
      ...g,
      ...summarizeGroup(g, byGroup.get(g.id) ?? []),
      tags: tagsByGroup.get(g.id) ?? [],
    }));
    const wantedStatuses = filters.status?.split(",").filter(Boolean) ?? [];
    const wantedTags = filters.tags?.split(",").filter(Boolean) ?? [];
    const createdWindow = dayWindow(filters.createdFrom, filters.createdTo);
    const scheduledWindow = dayWindow(filters.scheduledFrom, filters.scheduledTo);
    const createdBy = filters.createdBy?.trim().toLowerCase();
    return items.filter(
      (g) =>
        (wantedStatuses.length === 0 || wantedStatuses.includes(g.status)) &&
        wantedTags.every((tagId) => g.tags.some((t) => t.id === tagId)) &&
        (!createdBy || (g.created_by ?? "").toLowerCase().includes(createdBy)) &&
        (!filters.pendingOnly || g.progress.upcoming + g.progress.active > 0) &&
        (!createdWindow || inWindow(g.created_at, createdWindow)) &&
        (!scheduledWindow ||
          (byGroup.get(g.id) ?? []).some((c) => c.scheduled_at && inWindow(c.scheduled_at, scheduledWindow))),
    );
  }

  async get(id: string) {
    const group = await this.requireGroup(id);
    // Go through CampaignService.list so subcampaigns carry live seen/click stats.
    const { items } = await this.campaignService.list(1000, 0, { parentId: id, sortBy: "start", sortOrder: "asc" });
    const tags = (await this.tagRepo.forGroups([id])).get(id) ?? [];
    return { ...group, ...summarizeGroup(group, items as Child[]), tags, campaigns: items };
  }

  /** Throws unless new subcampaigns may be added to this parent. */
  async assertCanAddChildren(id: string) {
    const { group, summary } = await this.load(id);
    if (summary.status === "COMPLETED") {
      throw new CampaignGroupError("This parent campaign is completed. Duplicate it to start a new campaign structure.", 409);
    }
    if (group.status === "PAUSED") {
      throw new CampaignGroupError("This parent campaign is paused. Resume it before adding subcampaigns.", 409);
    }
  }

  /**
   * Creates a parent with new subcampaigns (drafted client-side) and/or existing campaigns.
   * Everything is written in one transaction; "send now" subcampaigns are queued only after commit.
   */
  async create(
    data: {
      name?: string;
      description?: string | null;
      campaignIds?: string[];
      campaigns?: CampaignDraft[];
      tagIds?: unknown;
    },
    createdBy?: string,
  ) {
    const name = data.name?.trim();
    if (!name) throw new CampaignGroupError("Name is required");
    const tagIds = await this.validTagIds(data.tagIds);

    const drafts = data.campaigns ?? [];
    if (drafts.length > MAX_DRAFTS) throw new CampaignGroupError(`At most ${MAX_DRAFTS} notifications can be created at once`);

    const attachIds = [...new Set(data.campaignIds ?? [])].filter((c) => UUID_RE.test(c));
    await this.assertAttachable(attachIds);

    const rows = [];
    for (const [i, d] of drafts.entries()) {
      const label = `Notification ${i + 1}`;
      if (!d || typeof d !== "object") throw new CampaignGroupError(`${label} is invalid`);
      if (!d.target_criteria || typeof d.target_criteria !== "object") throw new CampaignGroupError(`${label} has no audience`);
      if (!d.image_url && !(d.title?.trim() && d.body?.trim())) throw new CampaignGroupError(`${label} needs a title and text, or an image`);
      const scheduledAt = d.sendNow ? null : d.scheduled_at ? new Date(d.scheduled_at) : null;
      if (scheduledAt && Number.isNaN(scheduledAt.getTime())) throw new CampaignGroupError(`${label} has an invalid schedule`);

      rows.push({
        name: d.name?.trim() || `Campaign_${Date.now()}_${i + 1}`,
        title: d.title || " ",
        body: d.body || " ",
        image_url: d.image_url || null,
        target_criteria: d.target_criteria,
        additional_data: d.additional_data ?? {},
        // "Send now" rows start as DRAFT and are queued below, after the transaction commits.
        status: d.sendNow || !scheduledAt ? "DRAFT" : "SCHEDULED",
        scheduled_at: scheduledAt,
        total_count: await this.campaignService.getAudienceCount(d.target_criteria),
      });
    }

    const { group, campaignIds } = await this.groupRepo.createWithCampaigns(
      { name, description: data.description ?? null, created_by: createdBy ?? null },
      rows,
      attachIds,
    );
    await this.tagRepo.setForGroup(group.id, tagIds);

    const failedToQueue: string[] = [];
    for (const [i, d] of drafts.entries()) {
      if (!d.sendNow) continue;
      try {
        await this.campaignService.enqueueCampaign(campaignIds[i]);
      } catch (err) {
        logError(`[CampaignGroupService] Failed to queue campaign ${campaignIds[i]}: ${err}`);
        failedToQueue.push(campaignIds[i]);
      }
    }

    return { ...(await this.get(group.id)), failed_to_queue: failedToQueue };
  }

  private async assertAttachable(ids: string[], groupId?: string) {
    for (const cid of ids) {
      const campaign = await this.campaignRepo.getById(cid);
      if (!campaign || campaign.status === "DELETED") {
        throw new CampaignGroupError(`Campaign ${cid} not found`, 404);
      }
      if (campaign.parent_id && campaign.parent_id !== groupId) {
        throw new CampaignGroupError(`"${campaign.name || campaign.title}" already belongs to another parent campaign. Remove it there first.`, 409);
      }
    }
  }

  async update(id: string, data: { name?: string; description?: string | null; tagIds?: unknown }) {
    await this.requireGroup(id);
    const name = data.name?.trim();
    if (data.name !== undefined && !name) throw new CampaignGroupError("Name is required");
    await this.groupRepo.update(id, { name, description: data.description });
    if (data.tagIds !== undefined) await this.tagRepo.setForGroup(id, await this.validTagIds(data.tagIds));
    return this.get(id);
  }

  /** Soft-deletes the parent and detaches its campaigns; the campaigns themselves are kept. */
  async delete(id: string, options: { withNotifications?: boolean } = {}) {
    await this.requireGroup(id);
    const detached = await this.groupRepo.detach(id);
    if (options.withNotifications) {
      await Promise.all(detached.map(({ id: campaignId }) => this.campaignRepo.delete(campaignId)));
    }
    await this.groupRepo.update(id, { status: "DELETED" });
    return {
      detached: options.withNotifications ? 0 : detached.length,
      deleted: options.withNotifications ? detached.length : 0,
    };
  }

  async attach(id: string, campaignIds: string[]) {
    const ids = [...new Set(campaignIds)].filter((c) => UUID_RE.test(c));
    if (ids.length === 0) throw new CampaignGroupError("No valid campaigns selected");
    await this.assertCanAddChildren(id);
    await this.assertAttachable(ids, id);
    await this.groupRepo.attach(id, ids);
    return this.get(id);
  }

  async detach(id: string, campaignIds: string[]) {
    await this.requireGroup(id);
    const ids = campaignIds.filter((c) => UUID_RE.test(c));
    // Detached campaigns keep their current status (a paused one stays STOPPED and can be resumed on its own).
    await this.groupRepo.detach(id, ids);
    return this.get(id);
  }

  async pause(id: string) {
    const { group, summary } = await this.load(id);
    if (group.status === "PAUSED") throw new CampaignGroupError("Parent campaign is already paused", 409);
    if (summary.status === "COMPLETED") throw new CampaignGroupError("Parent campaign is already completed", 409);

    const stopped = await this.groupRepo.pauseChildren(id);
    for (const { id: cid } of stopped) emitCampaignStatus(cid, "STOPPED");
    await this.groupRepo.update(id, { status: "PAUSED" });
    return this.get(id);
  }

  async resume(id: string) {
    const group = await this.requireGroup(id);
    if (group.status !== "PAUSED") throw new CampaignGroupError("Parent campaign is not paused", 409);
    await this.resumeChildren(id);
    await this.groupRepo.update(id, { status: "ACTIVE" });
    return this.get(id);
  }

  /** Restart only the subcampaigns stopped by a parent pause; future schedules go back to SCHEDULED. */
  private async resumeChildren(id: string) {
    const paused = await this.groupRepo.getParentPausedChildren(id);
    await this.groupRepo.clearParentPausedFlag(id);
    for (const child of paused) {
      await this.campaignService.restartCampaign(child);
    }
  }

  /** Copies selected subcampaigns into the same parent as unscheduled drafts. */
  async duplicateChildren(id: string, campaignIds: string[], createdBy?: string) {
    await this.assertCanAddChildren(id);
    const ids = [...new Set(campaignIds)].filter((c) => UUID_RE.test(c));
    if (ids.length === 0) throw new CampaignGroupError("No valid campaigns selected");

    let created = 0;
    for (const cid of ids) {
      const c = await this.campaignRepo.getById(cid);
      if (!c || c.parent_id !== id || c.status === "DELETED") continue;
      await this.campaignRepo.create({
        name: `${c.name} (copy)`,
        title: c.title,
        body: c.body,
        image_url: c.image_url,
        target_criteria: c.target_criteria,
        additional_data: c.additional_data,
        status: "DRAFT",
        scheduled_at: null,
        total_count: Number(c.total_count || 0),
        published_by: createdBy ?? null,
        parent_id: id,
      });
      created++;
    }
    return { ...(await this.get(id)), duplicated: created };
  }

  /** Copies the parent and all its subcampaigns as unscheduled drafts. */
  async duplicate(id: string, createdBy?: string) {
    const { group, children } = await this.load(id);
    const copy = await this.groupRepo.create({
      name: `${group.name} (copy)`,
      description: group.description,
      created_by: createdBy ?? null,
    });

    for (const c of children) {
      await this.campaignRepo.create({
        name: c.name,
        title: c.title,
        body: c.body,
        image_url: c.image_url,
        target_criteria: c.target_criteria,
        additional_data: c.additional_data,
        status: "DRAFT",
        scheduled_at: null,
        total_count: Number(c.total_count || 0),
        published_by: createdBy ?? null,
        parent_id: copy.id,
      });
    }
    const tags = (await this.tagRepo.forGroups([id])).get(id) ?? [];
    await this.tagRepo.setForGroup(copy.id, tags.map((t) => t.id));
    return this.get(copy.id);
  }
}
