import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { hashPassword } from '../../utils/hash';


const prisma = new PrismaClient();

// GET /api/admin/settings
// Fetch store settings + current admin profile + preferences
export const getSettings = async (req: Request, res: Response) => {
  try {
    // 1. Fetch Store Config (Upsert ensures it exists)
    const storeSettings = await prisma.storeSettings.upsert({
      where: { id: 'store_config' },
      update: {},
      create: {
        storeName: 'Luxe Fabric Store',
        supportEmail: 'support@luxe.com',
        taxRate: 18.0
      }
    });

    // 2. Fetch Admin Profile (Assuming req.user.id is set by auth middleware)
    const adminId = (req as any).params?.id; 
    const adminProfile = await prisma.user.findUnique({
      where: { id: adminId },
      select: {
        fullName: true,
        email: true,
        notifyOrder: true,
        notifyStock: true,
        notifyReview: true
      }
    });

    if (!adminProfile) return res.status(404).json({ error: "Admin not found" });

    res.json({
      store: {
        ...storeSettings,
        taxRate: Number(storeSettings.taxRate)
      },
      account: {
        name: adminProfile.fullName,
        email: adminProfile.email
      },
      notifications: {
        orders: adminProfile.notifyOrder,
        stock: adminProfile.notifyStock,
        reviews: adminProfile.notifyReview
      }
    });

  } catch (error) {
    console.error("Get Settings Error:", error);
    res.status(500).json({ error: "Failed to fetch settings" });
  }
};

// PUT /api/admin/settings/store
export const updateStoreSettings = async (req: Request, res: Response) => {
  try {
    const { storeName, supportEmail, taxRate } = req.body;

    const updated = await prisma.storeSettings.update({
      where: { id: 'store_config' },
      data: {
        storeName,
        supportEmail,
        taxRate: parseFloat(taxRate)
      }
    });

    res.json(updated);
  } catch (error) {
    console.error("Update Store Error:", error);
    res.status(500).json({ error: "Failed to update store settings" });
  }
};

// PUT /api/admin/settings/account
export const updateAccount = async (req: Request, res: Response) => {
  try {
    const adminId = (req as any).params?.id;
    const { fullName, email, password } = req.body;

    const data: any = { fullName, email };

    // Only update password if provided
    if (password && password.length >= 6) {
      const hashedPassword = await hashPassword(password);
      data.password = hashedPassword;
    }

    const updatedAdmin = await prisma.user.update({
      where: { id: adminId },
      data,
      select: { id: true, fullName: true, email: true } 
    });

    res.json(updatedAdmin);
  } catch (error) {
    console.error("Update Account Error:", error);
    res.status(500).json({ error: "Failed to update account" });
  }
};

// PUT /api/admin/settings/notifications
export const updateNotifications = async (req: Request, res: Response) => {
  try {
    const adminId = (req as any).params?.id;
    const { notifyOrder, notifyStock, notifyReview } = req.body;

    const updated = await prisma.user.update({
      where: { id: adminId },
      data: {
        notifyOrder,
        notifyStock,
        notifyReview
      },
      select: { notifyOrder: true, notifyStock: true, notifyReview: true }
    });

    res.json(updated);
  } catch (error) {
    console.error("Update Notifications Error:", error);
    res.status(500).json({ error: "Failed to update notifications" });
  }
};