"use client";
import * as React from "react";
import { type ColumnDef } from "@tanstack/react-table";
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
import { Badge } from "@/components/ui/badge";
import { Clock, Activity, Globe, Zap, AlertCircle } from "lucide-react";
import { formatDateTime } from "@/lib/utils";
import { integrationLogTable } from "@/db/schema/integration-log";

// 확장된 타입 정의 (JOIN 결과)
type IntegrationLogWithIntegration = typeof integrationLogTable.$inferSelect & {
  code?: string;
  name?: string;
  type?: string;
  sourceSystem?: string;
  targetSystem?: string;
  status?: string;
};

export function getColumns(): ColumnDef<IntegrationLogWithIntegration>[] {
  return [
    {
      accessorKey: "name",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="통합명" />
      ),
      cell: ({ row }) => {
        const name = row.getValue("name") as string;
        const code = row.getValue("code") as string;
        return (
          <div className="flex items-center gap-2">
            <Activity className="h-4 w-4 text-muted-foreground" />
            <div className="flex flex-col">
              <span className="font-medium">{name || "-"}</span>
              {code && (
                <span className="text-xs text-muted-foreground">{code}</span>
              )}
            </div>
          </div>
        );
      },
      enableResizing: true,
      minSize: 150,
      size: 200,
    },
    {
      accessorKey: "type",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="타입" />
      ),
      cell: ({ row }) => {
        const type = row.getValue("type") as string;
        if (!type) return <span>-</span>;
        
        const typeMap: Record<string, { label: string; variant: "default" | "secondary" | "outline" }> = {
          rest_api: { label: "REST API", variant: "default" },
          soap: { label: "SOAP", variant: "secondary" },
          db_to_db: { label: "DB to DB", variant: "outline" },
        };
        
        const config = typeMap[type] || { label: type, variant: "outline" };
        
        return (
          <Badge variant={config.variant}>
            {config.label}
          </Badge>
        );
      },
      enableResizing: true,
      minSize: 100,
      size: 120,
    },
    {
      accessorKey: "status",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="상태" />
      ),
      cell: ({ row }) => {
        const status = row.getValue("status") as string;
        const statusMap: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
          success: { label: "성공", variant: "default" },
          failed: { label: "실패", variant: "destructive" },
          timeout: { label: "타임아웃", variant: "secondary" },
          pending: { label: "대기중", variant: "outline" },
        };
        
        const config = statusMap[status] || { label: status, variant: "outline" };
        
        return (
          <Badge variant={config.variant}>
            {config.label}
          </Badge>
        );
      },
      enableResizing: true,
      minSize: 100,
      size: 120,
    },
    {
      accessorKey: "requestMethod",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="메서드" />
      ),
      cell: ({ row }) => {
        const method = row.getValue("requestMethod") as string;
        if (!method) return <span>-</span>;
        
        const methodColors: Record<string, string> = {
          GET: "bg-blue-100 text-blue-800",
          POST: "bg-green-100 text-green-800",
          PUT: "bg-yellow-100 text-yellow-800",
          DELETE: "bg-red-100 text-red-800",
        };
        
        return (
          <span className={`px-2 py-1 rounded text-xs font-mono ${methodColors[method] || "bg-gray-100 text-gray-800"}`}>
            {method}
          </span>
        );
      },
      enableResizing: true,
      minSize: 80,
      size: 100,
    },
    {
      accessorKey: "httpStatusCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="상태코드" />
      ),
      cell: ({ row }) => {
        const statusCode = row.getValue("httpStatusCode") as number;
        if (!statusCode) return <span>-</span>;
        
        const isClientError = statusCode >= 400 && statusCode < 500;
        const isServerError = statusCode >= 500;
        
        let colorClass = "text-green-600";
        if (isClientError) colorClass = "text-yellow-600";
        if (isServerError) colorClass = "text-red-600";
        
        return (
          <span className={`font-mono text-sm ${colorClass}`}>
            {statusCode}
          </span>
        );
      },
      enableResizing: true,
      minSize: 100,
      size: 120,
    },
    {
      accessorKey: "responseTime",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="응답시간" />
      ),
      cell: ({ row }) => {
        const responseTime = row.getValue("responseTime") as number;
        if (!responseTime) return <span>-</span>;
        
        let colorClass = "text-green-600";
        if (responseTime > 1000) colorClass = "text-yellow-600";
        if (responseTime > 5000) colorClass = "text-red-600";
        
        return (
          <div className="flex items-center gap-2">
            <Zap className="h-4 w-4 text-muted-foreground" />
            <span className={`text-sm ${colorClass}`}>
              {responseTime}ms
            </span>
          </div>
        );
      },
      enableResizing: true,
      minSize: 100,
      size: 120,
    },
    {
      accessorKey: "executionTime",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="실행시간" />
      ),
      cell: ({ cell }) => {
        const executionTime = cell.getValue() as Date;
        return (
          <div className="flex items-center gap-2">
            <Clock className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm">{formatDateTime(executionTime)}</span>
          </div>
        );
      },
      enableResizing: true,
      minSize: 150,
      size: 180,
    },
    {
      accessorKey: "requestUrl",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="요청 URL" />
      ),
      cell: ({ row }) => {
        const url = row.getValue("requestUrl") as string;
        return (
          <div className="flex items-center gap-2">
            <Globe className="h-4 w-4 text-muted-foreground" />
            <div className="max-w-[200px] truncate text-sm">
              {url || "-"}
            </div>
          </div>
        );
      },
      enableResizing: true,
      minSize: 150,
      size: 200,
    },
    {
      accessorKey: "errorMessage",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="에러" />
      ),
      cell: ({ row }) => {
        const errorMessage = row.getValue("errorMessage") as string;
        if (!errorMessage) return <span>-</span>;
        
        return (
          <div className="flex items-center gap-2">
            <AlertCircle className="h-4 w-4 text-red-500" />
            <div className="max-w-[150px] truncate text-sm text-red-600">
              {errorMessage}
            </div>
          </div>
        );
      },
      enableResizing: true,
      minSize: 120,
      size: 150,
    },
  ];
} 