using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using CNCSystem.Data.Entities;

namespace CNCSystem.Web
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // 初始化数据库
            Database.SetInitializer<CNCBusinessDbContext>(null);
            Database.SetInitializer<CNCLLogDbContext>(null);

            // 确保数据库存在
            EnsureDatabaseCreated();
        }

        private void EnsureDatabaseCreated()
        {
            try
            {
                using (var context = new CNCBusinessDbContext())
                {
                    context.Database.CreateIfNotExists();
                }

                using (var logContext = new CNCLLogDbContext())
                {
                    logContext.Database.CreateIfNotExists();
                }
            }
            catch (Exception ex)
            {
                // 记录数据库初始化错误
                LogError("数据库初始化失败", ex);
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();
            LogError("应用程序错误", exception);
            
            // 如果是HttpException，设置HTTP状态码
            if (exception is HttpException httpException)
            {
                Response.StatusCode = httpException.GetHttpCode();
            }
            else
            {
                Response.StatusCode = 500;
            }
            
            Server.ClearError();
            
            // 重定向到错误页面
            Response.TrySkipIisCustomErrors = true;
            Server.TransferRequest("~/Error.aspx");
        }

        private void LogError(string message, Exception exception)
        {
            try
            {
                // 写入事件日志
                System.Diagnostics.EventLog.WriteEntry("Application", 
                    $"{message}: {exception.Message}", System.Diagnostics.EventLogEntryType.Error);
                
                // 写入文件日志
                var logPath = Server.MapPath("~/App_Data/Logs/Error.log");
                var logMessage = $"[{DateTime.Now}] {message}: {exception.Message}\n" +
                               $"Stack Trace: {exception.StackTrace}\n\n";
                
                System.IO.File.AppendAllText(logPath, logMessage);
            }
            catch
            {
                // 如果日志记录失败，忽略错误
            }
        }
    }
}