"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateNotifications = exports.updateAccount = exports.updateStoreSettings = exports.getSettings = void 0;
const client_1 = require("@prisma/client");
const hash_1 = require("../../utils/hash");
const prisma = new client_1.PrismaClient();
// GET /api/admin/settings
// Fetch store settings + current admin profile + preferences
const getSettings = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        // 1. Fetch Store Config (Upsert ensures it exists)
        const storeSettings = yield 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 = (_a = req.params) === null || _a === void 0 ? void 0 : _a.id;
        const adminProfile = yield 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: Object.assign(Object.assign({}, 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" });
    }
});
exports.getSettings = getSettings;
// PUT /api/admin/settings/store
const updateStoreSettings = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { storeName, supportEmail, taxRate } = req.body;
        const updated = yield 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" });
    }
});
exports.updateStoreSettings = updateStoreSettings;
// PUT /api/admin/settings/account
const updateAccount = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const adminId = (_a = req.params) === null || _a === void 0 ? void 0 : _a.id;
        const { fullName, email, password } = req.body;
        const data = { fullName, email };
        // Only update password if provided
        if (password && password.length >= 6) {
            const hashedPassword = yield (0, hash_1.hashPassword)(password);
            data.password = hashedPassword;
        }
        const updatedAdmin = yield 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" });
    }
});
exports.updateAccount = updateAccount;
// PUT /api/admin/settings/notifications
const updateNotifications = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const adminId = (_a = req.params) === null || _a === void 0 ? void 0 : _a.id;
        const { notifyOrder, notifyStock, notifyReview } = req.body;
        const updated = yield 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" });
    }
});
exports.updateNotifications = updateNotifications;
