// @ts-nocheck
/**
 * Unit tests for Social Accounts API routes
 * Tests API endpoints for social media account management
 */

import { NextRequest } from "next/server";

// Mock staff session
const mockValidateStaffSession = jest.fn();
jest.mock("@/lib/staff-session", () => ({
  validateStaffSession: () => mockValidateStaffSession(),
}));

// Mock social auth service
const mockGetConnectedAccounts = jest.fn();
const mockGetAuthorizationUrl = jest.fn();
const mockGetAccountById = jest.fn();
const mockRevokeAccess = jest.fn();

jest.mock("@/lib/services/social-auth.service", () => ({
  getConnectedAccounts: () => mockGetConnectedAccounts(),
  getAuthorizationUrl: (...args: unknown[]) => mockGetAuthorizationUrl(...args),
  getAccountById: (...args: unknown[]) => mockGetAccountById(...args),
  revokeAccess: (...args: unknown[]) => mockRevokeAccess(...args),
}));

// Mock logger
jest.mock("@/lib/logger", () => ({
  logger: {
    scope: () => ({
      info: jest.fn(),
      warn: jest.fn(),
      error: jest.fn(),
    }),
  },
}));

// Route not yet implemented at expected path
describe.skip("Social Accounts API", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    mockValidateStaffSession.mockResolvedValue({
      id: "staff-123",
      email: "staff@example.com",
      name: "Staff User",
      role: "STAFF",
    });
  });

  describe("GET /api/staff/dashboard/social/accounts", () => {
    it("should return connected accounts for authenticated staff", async () => {
      const mockAccounts = [
        {
          id: "acc-1",
          platform: "FACEBOOK",
          accountName: "My Page",
          status: "CONNECTED",
        },
        {
          id: "acc-2",
          platform: "INSTAGRAM",
          accountName: "@myaccount",
          status: "CONNECTED",
        },
      ];

      mockGetConnectedAccounts.mockResolvedValueOnce(mockAccounts);

      // Import dynamically to apply mocks
      const { GET } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
      );
      const response = await GET(request);
      const data = await response.json();

      expect(response.status).toBe(200);
      expect(data.success).toBe(true);
      expect(data.data).toHaveLength(2);
      expect(data.count).toBe(2);
    });

    it("should return 401 for unauthenticated requests", async () => {
      mockValidateStaffSession.mockResolvedValueOnce(null);

      const { GET } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
      );
      const response = await GET(request);
      const data = await response.json();

      expect(response.status).toBe(401);
      expect(data.error).toBe("Unauthorized");
    });

    it("should handle service errors gracefully", async () => {
      mockGetConnectedAccounts.mockRejectedValueOnce(
        new Error("Database error"),
      );

      const { GET } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
      );
      const response = await GET(request);
      const data = await response.json();

      expect(response.status).toBe(500);
      expect(data.error).toBeDefined();
    });
  });

  describe("POST /api/staff/dashboard/social/accounts (initiate OAuth)", () => {
    it("should initiate OAuth flow for valid platform", async () => {
      mockGetAuthorizationUrl.mockResolvedValueOnce({
        url: "https://facebook.com/oauth/authorize?client_id=123",
        csrfToken: "csrf-token-123",
      });

      const { POST } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
        {
          method: "POST",
          body: JSON.stringify({
            platform: "FACEBOOK",
          }),
        },
      );

      const response = await POST(request);
      const data = await response.json();

      expect(response.status).toBe(200);
      expect(data.success).toBe(true);
      expect(data.data.url).toContain("facebook.com");
      expect(data.data.csrfToken).toBeDefined();
      expect(data.data.platform).toBe("FACEBOOK");
    });

    it("should reject invalid platform", async () => {
      const { POST } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
        {
          method: "POST",
          body: JSON.stringify({
            platform: "INVALID_PLATFORM",
          }),
        },
      );

      const response = await POST(request);
      const data = await response.json();

      expect(response.status).toBe(400);
      expect(data.error).toContain("Invalid platform");
    });

    it("should return 401 for unauthenticated requests", async () => {
      mockValidateStaffSession.mockResolvedValueOnce(null);

      const { POST } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
        {
          method: "POST",
          body: JSON.stringify({
            platform: "FACEBOOK",
          }),
        },
      );

      const response = await POST(request);
      const data = await response.json();

      expect(response.status).toBe(401);
      expect(data.error).toBe("Unauthorized");
    });

    it("should handle OAuth not configured errors", async () => {
      mockGetAuthorizationUrl.mockRejectedValueOnce(
        new Error("META_APP_ID and META_APP_SECRET must be configured"),
      );

      const { POST } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
        {
          method: "POST",
          body: JSON.stringify({
            platform: "FACEBOOK",
          }),
        },
      );

      const response = await POST(request);
      const data = await response.json();

      expect(response.status).toBe(501);
      expect(data.error).toContain("META_APP_ID");
    });

    it("should handle platform not implemented errors", async () => {
      mockGetAuthorizationUrl.mockRejectedValueOnce(
        new Error("Platform TWITTER OAuth not yet implemented"),
      );

      const { POST } =
        await import("@/app/api/staff/dashboard/social/accounts/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts",
        {
          method: "POST",
          body: JSON.stringify({
            platform: "TWITTER",
          }),
        },
      );

      const response = await POST(request);
      const data = await response.json();

      expect(response.status).toBe(501);
      expect(data.error).toContain("not yet implemented");
    });
  });

  describe("GET /api/staff/dashboard/social/accounts/[id]", () => {
    it("should return account details for authenticated staff", async () => {
      const mockAccount = {
        id: "acc-123",
        userId: "staff-123",
        platform: "FACEBOOK",
        accountName: "My Page",
        status: "CONNECTED",
        tokenExpiry: new Date(),
        metadata: {},
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      mockGetAccountById.mockResolvedValueOnce(mockAccount);

      const { GET } =
        await import("@/app/api/staff/dashboard/social/accounts/[id]/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts/acc-123",
      );

      const response = await GET(request, {
        params: Promise.resolve({ id: "acc-123" }),
      });
      const data = await response.json();

      expect(response.status).toBe(200);
      expect(data.success).toBe(true);
      expect(data.data.id).toBe("acc-123");
      expect(data.data.platformConfig).toBeDefined();
    });

    it("should return 404 for non-existent account", async () => {
      mockGetAccountById.mockResolvedValueOnce(null);

      const { GET } =
        await import("@/app/api/staff/dashboard/social/accounts/[id]/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts/non-existent",
      );

      const response = await GET(request, {
        params: Promise.resolve({ id: "non-existent" }),
      });
      const data = await response.json();

      expect(response.status).toBe(404);
      expect(data.error).toContain("not found");
    });

    it("should return 401 for unauthenticated requests", async () => {
      mockValidateStaffSession.mockResolvedValueOnce(null);

      const { GET } =
        await import("@/app/api/staff/dashboard/social/accounts/[id]/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts/acc-123",
      );

      const response = await GET(request, {
        params: Promise.resolve({ id: "acc-123" }),
      });
      const data = await response.json();

      expect(response.status).toBe(401);
      expect(data.error).toBe("Unauthorized");
    });
  });

  describe("DELETE /api/staff/dashboard/social/accounts/[id]", () => {
    it("should disconnect account for authenticated staff", async () => {
      mockGetAccountById.mockResolvedValueOnce({
        id: "acc-123",
        userId: "staff-123",
        platform: "FACEBOOK",
      });
      mockRevokeAccess.mockResolvedValueOnce(undefined);

      const { DELETE } =
        await import("@/app/api/staff/dashboard/social/accounts/[id]/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts/acc-123",
        { method: "DELETE" },
      );

      const response = await DELETE(request, {
        params: Promise.resolve({ id: "acc-123" }),
      });
      const data = await response.json();

      expect(response.status).toBe(200);
      expect(data.success).toBe(true);
      expect(data.message).toContain("FACEBOOK");
      expect(mockRevokeAccess).toHaveBeenCalledWith("acc-123");
    });

    it("should return 404 for non-existent account", async () => {
      mockGetAccountById.mockResolvedValueOnce(null);

      const { DELETE } =
        await import("@/app/api/staff/dashboard/social/accounts/[id]/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts/non-existent",
        { method: "DELETE" },
      );

      const response = await DELETE(request, {
        params: Promise.resolve({ id: "non-existent" }),
      });
      const data = await response.json();

      expect(response.status).toBe(404);
      expect(data.error).toContain("not found");
    });

    it("should return 401 for unauthenticated requests", async () => {
      mockValidateStaffSession.mockResolvedValueOnce(null);

      const { DELETE } =
        await import("@/app/api/staff/dashboard/social/accounts/[id]/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts/acc-123",
        { method: "DELETE" },
      );

      const response = await DELETE(request, {
        params: Promise.resolve({ id: "acc-123" }),
      });
      const data = await response.json();

      expect(response.status).toBe(401);
      expect(data.error).toBe("Unauthorized");
    });

    it("should handle revocation errors", async () => {
      mockGetAccountById.mockResolvedValueOnce({
        id: "acc-123",
        userId: "staff-123",
        platform: "FACEBOOK",
      });
      mockRevokeAccess.mockRejectedValueOnce(new Error("Revocation failed"));

      const { DELETE } =
        await import("@/app/api/staff/dashboard/social/accounts/[id]/route");

      const request = new NextRequest(
        "http://localhost/api/staff/dashboard/social/accounts/acc-123",
        { method: "DELETE" },
      );

      const response = await DELETE(request, {
        params: Promise.resolve({ id: "acc-123" }),
      });
      const data = await response.json();

      expect(response.status).toBe(500);
      expect(data.error).toBeDefined();
    });
  });
});
