# -*- coding: utf-8 -*-
from odoo import api, fields, models
from odoo.exceptions import UserError


class PayslipGenerateWizard(models.TransientModel):
    _name = 'c2c.payslip.generate.wizard'
    _description = 'Generate Payslips Wizard'

    date_from = fields.Date(string='Period From', required=True)
    date_to = fields.Date(string='Period To', required=True)
    company_id = fields.Many2one(
        'res.company', string='Company', required=True,
        default=lambda self: self.env.company,
    )

    def action_generate_payslips(self):
        """Generate payslips for all employees with active contracts."""
        self.ensure_one()

        if self.date_from > self.date_to:
            raise UserError('Period From cannot be after Period To.')

        contracts = self.env['hr.contract'].search([
            ('state', '=', 'open'),
            ('company_id', '=', self.company_id.id),
            ('salary_structure_id', '!=', False),
            ('gross_salary', '>', 0),
        ])

        if not contracts:
            raise UserError(
                'No active contracts found with a salary structure and gross salary '
                'for company %s.' % self.company_id.name
            )

        Payslip = self.env['c2c.payslip']
        created_payslips = Payslip

        for contract in contracts:
            # Skip if payslip already exists for this employee and period
            existing = Payslip.search([
                ('employee_id', '=', contract.employee_id.id),
                ('date_from', '=', self.date_from),
                ('date_to', '=', self.date_to),
                ('company_id', '=', self.company_id.id),
            ], limit=1)
            if existing:
                continue

            payslip = Payslip.create({
                'employee_id': contract.employee_id.id,
                'contract_id': contract.id,
                'date_from': self.date_from,
                'date_to': self.date_to,
                'company_id': self.company_id.id,
            })
            created_payslips |= payslip

        if not created_payslips:
            raise UserError(
                'All eligible employees already have payslips for the selected period.'
            )

        return {
            'type': 'ir.actions.act_window',
            'name': 'Generated Payslips',
            'res_model': 'c2c.payslip',
            'view_mode': 'tree,form',
            'domain': [('id', 'in', created_payslips.ids)],
            'target': 'current',
        }
