using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Http;
using Newtonsoft.Json;

namespace CNCSystem.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                NullValueHandling = NullValueHandling.Include
            };

            // 启用跨域支持
            config.EnableCors();

            // 路由配置
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // 统一错误处理
            config.Filters.Add(new CustomExceptionFilter());
        }
    }

    public class CustomExceptionFilter : System.Web.Http.Filters.ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var exception = context.Exception;
            
            // 记录错误日志
            LogError(exception);

            // 根据异常类型返回不同的HTTP响应
            if (exception is ArgumentException)
            {
                context.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
                {
                    Content = new ObjectContent<object>(new
                    {
                        success = false,
                        message = exception.Message,
                        timestamp = DateTime.Now
                    }, new System.Net.Http.Formatting.JsonMediaTypeFormatter())
                };
            }
            else if (exception is UnauthorizedAccessException)
            {
                context.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
                {
                    Content = new ObjectContent<object>(new
                    {
                        success = false,
                        message = "未授权访问",
                        timestamp = DateTime.Now
                    }, new System.Net.Http.Formatting.JsonMediaTypeFormatter())
                };
            }
            else if (exception is System.Data.Entity.Infrastructure.DbUpdateException)
            {
                context.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError)
                {
                    Content = new ObjectContent<object>(new
                    {
                        success = false,
                        message = "数据库操作失败",
                        timestamp = DateTime.Now
                    }, new System.Net.Http.Formatting.JsonMediaTypeFormatter())
                };
            }
            else
            {
                context.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError)
                {
                    Content = new ObjectContent<object>(new
                    {
                        success = false,
                        message = "服务器内部错误",
                        timestamp = DateTime.Now
                    }, new System.Net.Http.Formatting.JsonMediaTypeFormatter())
                };
            }
        }

        private void LogError(Exception exception)
        {
            try
            {
                var logPath = HttpContext.Current.Server.MapPath("~/App_Data/Logs/ApiError.log");
                var logMessage = $"[{DateTime.Now}] {exception.GetType().Name}: {exception.Message}\n" +
                               $"Stack Trace: {exception.StackTrace}\n\n";
                
                System.IO.File.AppendAllText(logPath, logMessage);
            }
            catch
            {
                // 如果日志记录失败，忽略错误
            }
        }
    }
}