import { serverRequest } from "./serverConnection";

export interface ReportInput {
  reportType: string;
  targetType?: string;
  targetId?: string;
  contactName?: string;
  contactEmail?: string;
  contactPhone?: string;
  title: string;
  description: string;
  pageUrl?: string;
}

export interface AdminReportItem {
  id: number;
  userId?: number | null;
  username?: string | null;
  reportType?: string | null;
  targetType?: string | null;
  targetId?: string | null;
  contactName?: string | null;
  contactEmail?: string | null;
  contactPhone?: string | null;
  title: string;
  description: string;
  pageUrl?: string | null;
  status: string;
  ipAddress?: string | null;
  userAgent?: string | null;
  createdAt: string;
  updatedAt?: string | null;
}

function normalizeReport(raw: unknown): AdminReportItem {
  const item = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
  return {
    id: Number(item.id) || 0,
    userId: item.userId == null ? null : Number(item.userId),
    username: typeof item.username === "string" ? item.username : null,
    reportType: typeof item.reportType === "string" ? item.reportType : null,
    targetType: typeof item.targetType === "string" ? item.targetType : null,
    targetId: typeof item.targetId === "string" ? item.targetId : null,
    contactName: typeof item.contactName === "string" ? item.contactName : null,
    contactEmail: typeof item.contactEmail === "string" ? item.contactEmail : null,
    contactPhone: typeof item.contactPhone === "string" ? item.contactPhone : null,
    title: typeof item.title === "string" && item.title.trim() ? item.title : "未命名举报",
    description: typeof item.description === "string" ? item.description : "",
    pageUrl: typeof item.pageUrl === "string" ? item.pageUrl : null,
    status: typeof item.status === "string" && item.status.trim() ? item.status : "pending",
    ipAddress: typeof item.ipAddress === "string" ? item.ipAddress : null,
    userAgent: typeof item.userAgent === "string" ? item.userAgent : null,
    createdAt: typeof item.createdAt === "string" ? item.createdAt : "",
    updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : null,
  };
}

export const reportClient = {
  async submit(input: ReportInput): Promise<{ id: number; status: string; createdAt: string }> {
    const payload = await serverRequest<{ report: { id: number; status: string; createdAt: string } }>("reports", {
      method: "POST",
      body: input,
    });
    return payload.report;
  },

  async listAdminReports(): Promise<AdminReportItem[]> {
    const payload = await serverRequest<{ reports?: unknown[] }>("admin/reports");
    return Array.isArray(payload.reports) ? payload.reports.map(normalizeReport) : [];
  },
};
